Interview kitsBlog

Your dream job? Lets Git IT.
Interactive technical interview preparation platform designed for modern developers.

XGitHub

Platform

  • Categories

Resources

  • Blog
  • About the app
  • FAQ
  • Feedback

Legal

  • Privacy Policy
  • Terms of Service

© 2026 LetsGit.IT. All rights reserved.

LetsGit.IT/Categories/Algorithms
Algorithmshard

KMP vs naive substring search — what’s the core idea of KMP?

Tags
#kmp#string-search#pattern-matching
Back to categoryPractice quiz

Answer

KMP precomputes a prefix function (LPS) so when a mismatch happens, it shifts the pattern without re-checking characters. This makes search O(n+m) instead of O(n·m).

Advanced answer

Deep dive

KMP avoids repeated comparisons by reusing information about the pattern.

Core idea:

  • Precompute LPS (longest proper prefix that is also a suffix) for each prefix of the pattern.
  • On mismatch at pattern index j, jump j to LPS[j-1] instead of restarting from 0.

That guarantees the text index never moves backwards, so total complexity is O(n+m).

Common pitfalls

  • Off-by-one errors when building LPS.
  • Handling matches: after finding a match, set j = LPS[j-1] to continue searching.
  • Using KMP when a simpler approach is enough (engineering trade-off).

Related questions

Algorithms
KMP string search: how does the LPS/prefix table avoid re-checking characters?
#kmp#string#pattern-matching
Data Structures
What is a suffix array (or suffix tree) used for?
#strings#suffix-array#suffix-tree