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 AutomatonQuerying 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
- Start at the root with zero characters matched.
- For each pattern character, follow the arrow with that label.
- If an arrow is missing, stop — the pattern is not a substring.
- 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'
- From root follow 'a' → matched 1.
- Follow 'b' → matched 2.
- Follow 'a' → matched 3, pattern consumed.
- State counter says the prefix 'aba' ends at 2 positions.
Output: 'aba' IS a substring of 'ababa' (occurs 2 times)
Press ▶ Run to watch it step by step.
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: searchBehind 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
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
Ready for the next step?
See the same ideas in action — visualize the algorithms that operate on these structures, or take a guided course.