Data Structures · Visualization
Suffix Automaton: Introduction
Suffix Automaton
A suffix automaton (SAM) is the smallest machine that recognises every substring of a text. Time: O(n) to build, O(m) per substring query. Space: O(n) states and transitions.
Big-O: Build O(n) with ≤ 2n states; substring query O(m).
Suffix Automaton: Introduction
Suffix AutomatonA suffix automaton (SAM) is the smallest machine that recognises every substring of a text. Each new character adds at most two states, so the whole structure stays linear in size — yet walking it answers 'is this a substring?' in time proportional to the pattern, not the text.
How Suffix Automaton: Introduction Works
- Start with a single empty state (state 0, the root).
- Feed the text one character at a time, extending the machine.
- Each extension adds one or two states and a few labelled arrows.
- To test a pattern, follow its letters from the root — falling off means 'not a substring'.
Suffix Automaton: Introduction Worked Example
Input: Build a SAM for 'ababa'
- Add 'a' → states 0, 1.
- Add 'b' → states 0, 1, 2.
- Add 'a','b','a' → at most 6 states total.
- Walk 'bab' from the root: b → a → b all exist, so 'bab' is a substring.
Output: SAM for 'ababa' has 6 states; 'bab' found in 3 steps
Press ▶ Run to watch it step by step.
def sam_extend(st, last, ch):
cur = len(st)
st.append({'next': {}, 'link': -1}) # new state
p = last
while p != -1 and ch not in st[p]['next']:
st[p]['next'][ch] = cur
p = st[p]['link']
# (clone when needed) then fix links
return cur
text = "ababa"
# example: introSuffix Automaton: Introduction Time & Space Complexity
When to Use Suffix Automaton: Introduction
- Counting distinct substrings and finding the longest repeated substring
- The engine behind fast multi-pattern search where a trie would explode
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Ready for the next step?
See the same ideas in action — visualize the algorithms that operate on these structures, or take a guided course.