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 Automaton

A 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

  1. Start with a single empty state (state 0, the root).
  2. Feed the text one character at a time, extending the machine.
  3. Each extension adds one or two states and a few labelled arrows.
  4. 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'

  1. Add 'a' → states 0, 1.
  2. Add 'b' → states 0, 1, 2.
  3. Add 'a','b','a' → at most 6 states total.
  4. 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

📖 Introduction: this is an overview of the topic, so there's nothing to run here. Pick an operation from the side menu to see a live, step-by-step animation.
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: intro

Suffix Automaton: Introduction Time & Space Complexity

TimeO(n) to build, O(m) per substring query
SpaceO(n) states and transitions

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

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.