An FM-index uses a sorted suffix order and its last-column transform to search a pattern backwards. For each character, a first-column offset C gives the start of that character's block in sorted order, while a rank table counts its occurrences before any last-column position. The current suffix interval [left,right) becomes [C[c]+rank(c,left), C[c]+rank(c,right)) when character c is prepended. After all pattern characters are processed, interval width is the exact occurrence count. The example retains the full suffix array to locate positions and stores complete prefix-rank arrays for each character. It is an index mechanics model, not a compressed production FM-index. A single sentinel terminates the text and is forbidden in the input and pattern.
FM-index backward search: narrow a suffix interval by character
Operational case
The incident string cabacaba contains aba at offsets one and five. Backward search narrows the suffix interval to two rows, then the retained suffix positions report [1,5]. A pattern with a character absent from the alphabet has an empty interval. An empty pattern is rejected rather than assigned a special occurrence convention. The exact count includes overlapping matches when they exist. If the sentinel appeared inside the text, suffix order would no longer describe one uniquely terminated string, so the constructor fails before publishing the index. Text edits change the last column and rank tables and require reconstruction.
Working Python program
class IncidentFMIndex:
def __init__(self, text):
if "\0" in text:
raise ValueError("sentinel may not appear in text")
self.text_length = len(text)
indexed = text + "\0"
self.suffix_positions = sorted(range(len(indexed)), key=lambda position: indexed[position:])
self.last_column = "".join(indexed[position - 1] for position in self.suffix_positions)
alphabet = sorted(set(indexed))
frequencies = {letter: indexed.count(letter) for letter in alphabet}
self.first_offset = {}
running = 0
for letter in alphabet:
self.first_offset[letter] = running
running += frequencies[letter]
self.rank = {}
for letter in alphabet:
counts = [0]
for observed in self.last_column:
counts.append(counts[-1] + (observed == letter))
self.rank[letter] = counts
def _matching_suffix_interval(self, pattern):
if not pattern or "\0" in pattern:
raise ValueError("pattern must be nonempty and exclude the sentinel")
left, right = 0, len(self.suffix_positions)
for letter in reversed(pattern):
if letter not in self.first_offset:
return 0, 0
left = self.first_offset[letter] + self.rank[letter][left]
right = self.first_offset[letter] + self.rank[letter][right]
if left == right:
break
return left, right
def count(self, pattern):
left, right = self._matching_suffix_interval(pattern)
return right - left
def positions(self, pattern):
left, right = self._matching_suffix_interval(pattern)
return sorted(position for position in self.suffix_positions[left:right]
if position < self.text_length)
if __name__ == "__main__":
index = IncidentFMIndex("cabacaba")
print("aba count:", index.count("aba"))
print("aba positions:", index.positions("aba"))
print("xyz count:", index.count("xyz"))Output
aba count: 2
aba positions: [1, 5]
xyz count: 0Time, space, and tradeoff
Backward counting takes O(M) time for a pattern of length M because every rank lookup is an array access. Locating K matches takes O(K log K) here to sort their original positions. The deliberately simple suffix-string sorting construction has an O(N-squared log N) upper-bound time and large temporary cost; full rank arrays use O(N times alphabet size) memory, plus O(N) suffix positions. Production compressed indexes replace these arrays with compact rank structures and sampled positions, changing locate costs. This lesson isolates the exact backward interval rule rather than claiming compression or fast construction in Python.
Common Mistakes
- Do not allow the sentinel inside text or pattern.
- Do not mix inclusive and half-open suffix interval boundaries.
- Do not call full rank arrays a compressed index.
- Do not assume counting positions and locating positions have the same cost.
Connected lessons
- Trees and Heaps
- Data Structures
- Suffix arrays: indexed substring search and adjacent LCP
- Bitvector rank and select: count and locate set bits
- Wavelet matrices: count frequencies and find subarray quantiles
- Projects
- Quizzes
Compare its update and query contract with Block-max postings: skip safe document-score regions, Piecewise interpolation indexes: predict a bounded rank window, Euler-tour RMQ: answer static common ancestors in constant query time, then complete the structure audit and decision quiz.
