#1392
Longest Happy Prefix
HardStringRolling HashString MatchingHash FunctionString MatchingPrefix Function
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
Using the KMP (Knuth-Morris-Pratt) algorithm's prefix table, we can efficiently find the longest prefix that is also a suffix without redundant comparisons.
⚙️
Algorithm
3 steps- 1Step 1: Create a prefix table (LPS array) that stores the length of the longest proper prefix which is also a suffix for every substring of s.
- 2Step 2: The last value in the LPS array gives the length of the longest happy prefix.
- 3Step 3: Return the substring of s from the start to the length found in the LPS array.
solution.py13 lines
1def longest_happy_prefix(s):
2 n = len(s)
3 lps = [0] * n
4 j = 0
5 for i in range(1, n):
6 while j > 0 and s[i] != s[j]:
7 j = lps[j - 1]
8 if s[i] == s[j]:
9 j += 1
10 lps[i] = j
11 else:
12 lps[i] = 0
13 return s[:lps[-1]]ℹ
Complexity note: The time complexity is O(n) because we traverse the string once to build the LPS array. The space complexity is O(n) due to the storage of the LPS array.
- 1Understanding the difference between prefixes and suffixes is crucial.
- 2The KMP algorithm's LPS array is a powerful tool for efficiently solving string problems.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.