Java String Program · S64
Pattern Search Using the KMP Algorithm in Java
The naive search moves back in the text after every mismatch. KMP never does: a precomputed table tells it how much of the pattern is already matched, so the text is read only once.
Problem Statement
Given a text and a pattern, return the index where the pattern first occurs in the text, or -1 if it does not occur. Do it in time proportional to the length of the text plus the pattern.
An empty pattern matches at index 0, like String.indexOf("").
Input/Output Examples
text = "javabytechie", pattern = "tech"Output6Explanation: tech starts at index 6.text = "aaaaab", pattern = "aab"Output3Explanation: the naive search restarts many times; KMP keeps the matched "a".text = "abc", pattern = "d"Output-1Explanation: d never occurs.Visual Explanation
| pattern | a | b | a | b | d |
|---|---|---|---|---|---|
| lps | 0 | 0 | 1 | 2 | 0 |
"ababd": lps[i] is the length of the longest proper prefix of pattern[0..i] that is also a suffix of it. At index 3, "abab" ends with its own prefix "ab".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.
Approach 1: Knuth-Morris-Pratt (Recommended)
Idea: build the LPS (longest proper prefix that is also a suffix) table, then scan the text once, falling back in the pattern on mismatches.
- Build
lps: extend the current border when characters match; otherwise fall back withlen = lps[len - 1]. - Scan the text with
i; on a mismatch, setj = lps[j - 1]until the characters match orjis 0. - On a match, advance
j; whenjreaches the pattern length, returni - m + 1.
Time: O(n + m) · Space: O(m).
Approach 2: Naive Search
Idea: try every alignment of the pattern against the text and compare character by character.
- For each start position in the text, compare the pattern from its first character.
- Stop at the first mismatch and move the start one step right.
- Return the start when every character matches.
Time: O(n × m) · Space: O(1).
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.
Approach 1: Knuth-Morris-Pratt (Recommended)
Each fall-back step reduces j, and j grows by at most one per text character, so the total work is linear.
public class KmpSearch {
// lps[i] = length of the longest proper prefix of pattern[0..i] that is also a suffix
static int[] buildLps(String p) {
int[] lps = new int[p.length()];
int len = 0;
for (int i = 1; i < p.length(); i++) {
while (len > 0 && p.charAt(i) != p.charAt(len)) {
len = lps[len - 1]; // fall back to a shorter border
}
if (p.charAt(i) == p.charAt(len)) {
len++;
}
lps[i] = len;
}
return lps;
}
// Never moves backwards in the text: on a mismatch, only the pattern index falls back
static int indexOf(String text, String p) {
if (p.isEmpty()) {
return 0;
}
int[] lps = buildLps(p);
int j = 0;
for (int i = 0; i < text.length(); i++) {
while (j > 0 && text.charAt(i) != p.charAt(j)) {
j = lps[j - 1];
}
if (text.charAt(i) == p.charAt(j)) {
j++;
}
if (j == p.length()) {
return i - p.length() + 1;
}
}
return -1;
}
public static void main(String[] args) {
String[][] cases = {{"javabytechie", "tech"}, {"aaaaab", "aab"}, {"abc", "d"}};
for (String[] c : cases) {
System.out.println("text=\"" + c[0] + "\", pattern=\"" + c[1] + "\" -> " + indexOf(c[0], c[1]));
}
System.out.println("lps(\"aab\") = " + java.util.Arrays.toString(buildLps("aab")));
}
}
text="javabytechie", pattern="tech" -> 6
text="aaaaab", pattern="aab" -> 3
text="abc", pattern="d" -> -1
lps("aab") = [0, 1, 0]
Time complexity: O(n + m) · Space complexity: O(m).
Approach 2: Naive Search
Fine for short patterns, but inputs like "aaaa…ab" make it repeat almost the whole pattern at every position. The program also computes the LPS table directly from its definition, to check the fast version.
public class NaiveSearch {
// Tries every alignment and compares character by character: O(n * m)
static int indexOf(String text, String p) {
for (int start = 0; start + p.length() <= text.length(); start++) {
int j = 0;
while (j < p.length() && text.charAt(start + j) == p.charAt(j)) {
j++;
}
if (j == p.length()) {
return start;
}
}
return -1;
}
static int[] buildLps(String p) {
int[] lps = new int[p.length()]; // computed directly from the definition
for (int i = 0; i < p.length(); i++) {
for (int len = i; len > 0; len--) {
if (p.substring(0, len).equals(p.substring(i + 1 - len, i + 1))) {
lps[i] = len;
break;
}
}
}
return lps;
}
public static void main(String[] args) {
String[][] cases = {{"javabytechie", "tech"}, {"aaaaab", "aab"}, {"abc", "d"}};
for (String[] c : cases) {
System.out.println("text=\"" + c[0] + "\", pattern=\"" + c[1] + "\" -> " + indexOf(c[0], c[1]));
}
System.out.println("lps(\"aab\") = " + java.util.Arrays.toString(buildLps("aab")));
}
}
text="javabytechie", pattern="tech" -> 6
text="aaaaab", pattern="aab" -> 3
text="abc", pattern="d" -> -1
lps("aab") = [0, 1, 0]
Time complexity: O(n × m) · Space complexity: O(1).
Complexity Analysis
| Approach | Time Complexity | Space Complexity |
|---|---|---|
| Knuth-Morris-Pratt | O(n + m) | O(m) |
| Naive Search | O(n × m) | O(1) |
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.