Skip to content
  • Dashboard
  • Review
  • Go: plan & chat
  • Roadmap
  • Patterns & lessons49
  • Sheets
  • Problems1.5k
  • Ascend
  • Toolkit
  • Core CS + SQL
  • System Design
  • Machine Coding
  • Interview hub
  • Mock interview
  • Companies & OA
  • Leaderboard
  • Battles
  • College Cup
  • People

Keep your progress

Sync across devices with a free account.

Sign upSign in
Patterns & lessons
Sign inSign up
Patterns/Strings & Tries/Trie (Prefix Tree)

Technique

Aho-Corasick Automaton

Build a trie of patterns plus KMP-style failure links so one pass over the text finds all occurrences of all patterns.

Learn firstTrie (Prefix Tree)String Matching (KMP / Z / Rabin-Karp)Graph BFS / DFS
0%
mastery
0/5 solved
Practise nextCounting Patterns
IdeaPracticePitfalls

Recognise it

The signal

many patterns, one text

  1. 1Brute force

    Run KMP once per pattern.

  2. 2The observation

    Per-pattern scans: failure links share partial matches across patterns.

  3. 3Why it works

    At each text position, the current state is the longest pattern-trie prefix that is a suffix of the text read.

Reach for it when

  • +count occurrences of each dictionary word
  • +DP over text avoiding forbidden words

Not when

  • ×single pattern (KMP)
  • ×substring queries on the text (suffix-array)

Practice

Next

Counting Patterns

0/5 solved
  • Finding PatternsCSESMedium
  • Counting PatternsCSESHard
  • Pattern PositionsCSESHard
  • Strings Containing Exactly B Given WordsMedia.netOAHard
  • You Are Given Some Strings...Codeforces2400

Pitfalls

Misconceptions

  • !forgetting to propagate counts along output/failure links
Go deeperresources

Resources

  • Prefix function (KMP)cp-algorithms · article
  • Z-functioncp-algorithms · article
  • String hashingcp-algorithms · article
  • Trie explore cardLeetCode · course
  • String cheatsheetTech Interview Handbook · article
TodayReviewPatternsProblems