Data Structures · Visualization
Suffix Automaton: Build
Suffix Automaton
Building extends the machine character by character. Time: O(1) amortised per character, O(n) total. Space: O(n) — at most 2n states.
Big-O: Build O(n) with ≤ 2n states; substring query O(m).
Suffix Automaton: Build
Suffix AutomatonBuilding extends the machine character by character. Each new character creates one fresh state for the whole new prefix, then fixes suffix links — the shortcut arrows that remember 'the longest smaller ending here'. Cloning a state (at most once per character) is what keeps the size linear.
How Build Works
- Create a new state for the entire prefix seen so far.
- Walk suffix links from the previous end, adding the missing arrow.
- If an arrow already exists to a state that is 'too long', clone it.
- Redirect the suffix links through the new (or cloned) state.
Build Worked Example
Input: Extend the SAM of 'ab' with 'a'
- New state 3 stands for the prefix 'aba'.
- Add 'a'-arrows along suffix links until one already has 'a'.
- State 1 already points 'a' somewhere too long → clone it as state 4.
- Point the new suffix links at states 3 and 4.
Output: SAM grows from 3 to 5 states after adding 'a'
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: buildBehind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
Build Time & Space Complexity
When to Use Build
- Streaming text indexes that grow as data arrives
- Preprocessing for repeated-substring analytics on genomes and logs
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.