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 Automaton

Building 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

  1. Create a new state for the entire prefix seen so far.
  2. Walk suffix links from the previous end, adding the missing arrow.
  3. If an arrow already exists to a state that is 'too long', clone it.
  4. Redirect the suffix links through the new (or cloned) state.

Build Worked Example

Input: Extend the SAM of 'ab' with 'a'

  1. New state 3 stands for the prefix 'aba'.
  2. Add 'a'-arrows along suffix links until one already has 'a'.
  3. State 1 already points 'a' somewhere too long → clone it as state 4.
  4. Point the new suffix links at states 3 and 4.

Output: SAM grows from 3 to 5 states after adding 'a'

Try your own input
SAM: Introduction
The smallest machine recognising every substring: O(n) states, O(m) queries.
0
len≤0
Current state Last (longest prefix) ↩ suffix link
SAM: Introduction
Press ▶ Run to watch it step by step.
Python · Suffix Automaton in Code
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: build
Input: Extend the SAM of 'ab' with 'a'

Behind 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

TimeO(1) amortised per character, O(n) total
SpaceO(n) — at most 2n states

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

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits

Ready for the next step?

See the same ideas in action — visualize the algorithms that operate on these structures, or take a guided course.