Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Break down a hard problem into reliable checkpoints, edge-case handling, and complexity trade-offs.
A string is called a happy prefix if is a non-empty prefix which is also a suffix (excluding itself).
Given a string s, return the longest happy prefix of s. Return an empty string "" if no such prefix exists.
Example 1:
Input: s = "level"
Output: "l"
Explanation: s contains 4 prefix excluding itself ("l", "le", "lev", "leve"), and suffix ("l", "el", "vel", "evel"). The largest prefix which is also suffix is given by "l".
Example 2:
Input: s = "ababab" Output: "abab" Explanation: "abab" is the largest prefix which is also suffix. They can overlap in the original string.
Constraints:
1 <= s.length <= 105s contains only lowercase English letters.Problem summary: A string is called a happy prefix if is a non-empty prefix which is also a suffix (excluding itself). Given a string s, return the longest happy prefix of s. Return an empty string "" if no such prefix exists.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: String Matching
"level"
"ababab"
sum-of-scores-of-built-strings)maximum-deletions-on-a-string)minimum-time-to-revert-word-to-initial-state-ii)minimum-time-to-revert-word-to-initial-state-i)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #1392: Longest Happy Prefix
class Solution {
private long[] p;
private long[] h;
public String longestPrefix(String s) {
int base = 131;
int n = s.length();
p = new long[n + 10];
h = new long[n + 10];
p[0] = 1;
for (int i = 0; i < n; ++i) {
p[i + 1] = p[i] * base;
h[i + 1] = h[i] * base + s.charAt(i);
}
for (int l = n - 1; l > 0; --l) {
if (get(1, l) == get(n - l + 1, n)) {
return s.substring(0, l);
}
}
return "";
}
private long get(int l, int r) {
return h[r] - h[l - 1] * p[r - l + 1];
}
}
// Accepted solution for LeetCode #1392: Longest Happy Prefix
func longestPrefix(s string) string {
base := 131
n := len(s)
p := make([]int, n+10)
h := make([]int, n+10)
p[0] = 1
for i, c := range s {
p[i+1] = p[i] * base
h[i+1] = h[i]*base + int(c)
}
for l := n - 1; l > 0; l-- {
prefix, suffix := h[l], h[n]-h[n-l]*p[l]
if prefix == suffix {
return s[:l]
}
}
return ""
}
# Accepted solution for LeetCode #1392: Longest Happy Prefix
class Solution:
def longestPrefix(self, s: str) -> str:
for i in range(1, len(s)):
if s[:-i] == s[i:]:
return s[i:]
return ''
// Accepted solution for LeetCode #1392: Longest Happy Prefix
impl Solution {
pub fn longest_prefix(s: String) -> String {
let n = s.len();
for i in (0..n).rev() {
if s[0..i] == s[n - i..n] {
return s[0..i].to_string();
}
}
String::new()
}
}
// Accepted solution for LeetCode #1392: Longest Happy Prefix
function longestPrefix(s: string): string {
const n = s.length;
for (let i = n - 1; i >= 0; i--) {
if (s.slice(0, i) === s.slice(n - i, n)) {
return s.slice(0, i);
}
}
return '';
}
Use this to step through a reusable interview workflow for this problem.
At each of the n starting positions in the text, compare up to m characters with the pattern. If a mismatch occurs, shift by one and restart. Worst case (e.g., searching "aab" in "aaaa...a") checks m characters at nearly every position: O(n × m).
KMP and Z-algorithm preprocess the pattern in O(m) to build a failure/Z-array, then scan the text in O(n) — never backtracking. Total: O(n + m). Rabin-Karp uses rolling hashes for O(n + m) expected time. All beat the O(n × m) brute force of checking every position.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.