KMP String Matching | Algorithm Interview | Skill-Lync Resources
Hard Algorithms String Algorithms

Explain the KMP string matching algorithm.

Answer

Knuth-Morris-Pratt achieves O(n+m) string matching by preprocessing pattern to build failure function (LPS array) - longest proper prefix which is also suffix. During search, when mismatch occurs, use LPS to skip characters already matched instead of restarting. LPS construction is O(m), matching is O(n). Key insight: we never need to backtrack in the text, only in the pattern using precomputed information.

Master These Concepts with IIT Certification
IIT Certified

Master These Concepts with IIT Certification

175+ hours of industry projects. Get placed at Bosch, Tata Motors, L&T and 500+ companies.

Relevant for Roles

Senior Software Engineer Algorithm Developer Search Engineer