← All Exercises

KMP Pattern Matching

advancedjavascript~25min

Background

KMP avoids rescanning text by reusing prefix information, making it a foundation for search boxes, DNA matching, and log filters.

Problem

Given a text and a pattern, return every starting index where the pattern occurs, including overlapping occurrences, using KMP.

Input

Two strings: text and pattern, each up to 100000 characters.

Output

An ascending array of zero-based starting indices; an empty array when the pattern is absent or empty.

Sample tests

Sample 1

Input: text = "ababcababc", pattern = "abab"
Expected: [0,5]

Sample 2

Input: text = "aaaa", pattern = "aa"
Expected: [0,1,2]

Sample 3

Input: text = "abc", pattern = "d"
Expected: []

Your solution

Learning objective

Build and apply the LPS prefix table to achieve O(n + m) substring search with overlap support.