00:00

Problem Statement

Input/Output Examples

Visual Explanation

If a mismatch happens right after matching "abab", the last two matched characters are already "ab", which is how the pattern starts. KMP continues from pattern index 2 instead of starting over, and the text pointer never moves back.

Approaches

KMP preprocesses the pattern so the search never re-reads the text. The naive search is shown for comparison.

Java Solutions

Each tab is a complete program that runs on Java 17 or later. Both programs print the same output for the same inputs.

Complexity Analysis

Here n is the length of the text and m the length of the pattern. Building the table costs O(m) and the search O(n), because neither index ever moves backwards in the text.

Interview Tips and Recommended Approach

  • Define LPS precisely. "Longest proper prefix that is also a suffix"; the whole string does not count.
  • Explain why it is linear. The text index only moves forward, and fall-backs are paid for by earlier advances.
  • Know when to use it. String.indexOf() is fast in practice; KMP guarantees linear time on adversarial inputs.
  • Reuse the LPS table. It also solves the shortest palindrome and repeated substring pattern problems.

Recommended Approach: Knuth-Morris-Pratt

Why: it guarantees linear time on every input, and its LPS table is a reusable tool for many other string problems.