Compute the Longest Prefix Suffix (LPS) array for KMP algorithm.
Problem Statement
Examples
Input: pattern = "abcab"
Output: [0, 0, 0, 1, 2]
Explanation: Combining the input according to KMP Algorithm or LPS array logic yields [0, 0, 0, 1, 2].
Input: pattern = "aaaa"
Output: [0, 1, 2, 3]
Explanation: Combining the input according to KMP Algorithm or LPS array logic yields [0, 1, 2, 3].
Complexity
Time Complexity: O(N)
Space Complexity: O(N)
Hints
Editorial & Approach
Problem Overview & Intuition
The Longest Prefix Suffix (LPS) array allows KMP to avoid re-examining characters upon mismatch. By falling back to len = lps[len - 1] rather than resetting to 0, construction runs in linear O(N) time.
Step-by-Step Approach
- Initialize
lps = new Array(n).fill(0),len = 0, andi = 1. - While
i < n: - If
pattern[i] === pattern[len]:len++,lps[i] = len,i++. - Else if
len !== 0: fall backlen = lps[len - 1]without incrementingi. - Else:
lps[i] = 0,i++. - Return
lps.
Optimal Implementation (JavaScript)
function computeLPSArray(pattern) {
const n = pattern.length;
const lps = new Array(n).fill(0);
let len = 0, i = 1;
while (i < n) {
if (pattern[i] === pattern[len]) {
len++;
lps[i] = len;
i++;
} else {
if (len !== 0) {
len = lps[len - 1];
} else {
lps[i] = 0;
i++;
}
}
}
return lps;
}
Complexity Analysis
Edge Cases & Corner Traps Handled
- All identical characters "aaaa": lps = [0, 1, 2, 3].
- No repeating prefixes: all zeroes.