ExamAdda Logo

Pattern Matching Using KMP Algorithm

Medium

Given a string text and a string pattern, find all starting indices where pattern occurs in text.

Use the Knuth-Morris-Pratt (KMP) algorithm to perform pattern matching efficiently. If the pattern does not occur in the text, return an empty array.

The indices are zero-based and must be returned in ascending order. Overlapping matches should also be included.

Example 1

Input

text = "ababcabcabababd"
pattern = "ababd"

Output

[10]

Explanation

The pattern "ababd" occurs in the text starting at index 10.

Example 2

Input

text = "aaaaa"
pattern = "aa"

Output

[0, 1, 2, 3]

Explanation

The pattern "aa" occurs at indices 0, 1, 2, and 3. Overlapping matches are included.

Constraints

1 <= text.length <= 10^5
1 <= pattern.length <= 10^5
pattern.length <= text.length
text and pattern contain English letters.

Hints:

Hint 1

Build an LPS (Longest Proper Prefix that is also a Suffix) array for the pattern.

Hint 2

When a mismatch occurs, use the LPS array to avoid comparing previously matched characters again. Continue searching to find overlapping occurrences.

Author & Technical Reviewer

Chatla Jithin Sri Surya

Written by: Chatla Jithin Sri Surya

Chatla Jithin Sri Surya

Technically reviewed by: Chatla Jithin Sri Surya

Published

Oct 27, 2026

Last updated

Oct 27, 2026

Last technically reviewed

Oct 27, 2026

Content Verification Methodology

Definitions and complexity claims were checked against authoritative computer-science references. Code examples were compiled and tested with standard, boundary and edge-case inputs.

Report a correction:editorial@examadda.org
Auto
Loading editor...
Input

Expected Output