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/String Matching (KMP / Z / Rabin-Karp)

Technique

Suffix Array + LCP

Sort all suffixes (O(n log n)) and compute LCP of neighbours to answer distinct-substring, repeated-substring, and pattern-count questions.

Learn firstString Matching (KMP / Z / Rabin-Karp)Rolling / Polynomial String Hashing
0%
mastery
0/10 solved
Practise nextDistinct Substrings
IdeaPracticePitfalls

Recognise it

The signal

count distinct substrings

  1. 1Brute force

    Sort all suffixes by direct comparison O(n2 log n).

  2. 2The observation

    Direct comparisons: doubling sorts by first 2k characters reusing ranks.

  3. 3Why it works

    After round k, suffixes are sorted by their first 2k characters.

Reach for it when

  • +longest repeated substring
  • +k-th lexicographic substring
  • +many pattern searches in one text

Not when

  • ×single pattern search (KMP)
  • ×online appends (suffix automaton)

Practice

Next

Distinct Substrings

0/10 solved
  • Distinct SubstringsCSESHard
  • Substring Order ICSESHard
  • Substring Order IICSESHard
  • StringCodeforces2300
  • Longest Duplicate SubstringHard
  • Repeating SubstringCSESHard
  • Substring DistributionCSESHard
  • Counting PatternsCSESHard
  • Pattern PositionsCSESHard
  • Inverse Suffix ArrayCSESHard

Pitfalls

Misconceptions

  • !mixing up rank and sa arrays
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