Data Structures · Visualization

Suffix Automaton: Substring Query

Suffix Automaton

Querying is just a walk: start at the root and follow one arrow per pattern character. Time: O(m) for a pattern of length m. Space: O(1) extra besides the automaton.

Big-O: Build O(n) with ≤ 2n states; substring query O(m).

Suffix Automaton: Substring Query

Suffix Automaton

Querying is just a walk: start at the root and follow one arrow per pattern character. If every arrow exists you have found the pattern; the first missing arrow proves it never occurs. Each step also tells you how many times the matched prefix appears (stored on the state).

How Substring Query Works

  1. Start at the root with zero characters matched.
  2. For each pattern character, follow the arrow with that label.
  3. If an arrow is missing, stop — the pattern is not a substring.
  4. If you consume the whole pattern, it occurs; the state's counter gives how often.

Substring Query Worked Example

Input: Query 'aba' in the SAM of 'ababa'

  1. From root follow 'a' → matched 1.
  2. Follow 'b' → matched 2.
  3. Follow 'a' → matched 3, pattern consumed.
  4. State counter says the prefix 'aba' ends at 2 positions.

Output: 'aba' IS a substring of 'ababa' (occurs 2 times)

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 substring(st, pat):
    v = 0
    for ch in pat:
        if ch not in st[v]['next']:
            return False   # fell off: absent
        v = st[v]['next'][ch]
    return True            # consumed: present

# O(m) for pattern length m
# example: search
Input: Query 'aba' in the SAM of 'ababa'

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.

Substring Query Time & Space Complexity

TimeO(m) for a pattern of length m
SpaceO(1) extra besides the automaton

When to Use Substring Query

  • Spell-checkers and autocomplete that must answer in milliseconds
  • Plagiarism and duplicate-code detectors over huge corpora

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.