LeetCode 1392: Longest Happy Prefix Solution

Master LeetCode problem 1392 (Longest Happy Prefix), a hard challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

Problem Explanation

Explanation

To find the longest happy prefix of a given string s, we can use the KMP (Knuth-Morris-Pratt) algorithm. The idea is to preprocess s and find the longest prefix suffix array for each index. The longest happy prefix will be the substring from index 0 to the last index of the longest prefix suffix array.

  1. We initialize variables i and j to 1 and 0 respectively.
  2. While iterating through the string:
    • If s.charAt(i) equals s.charAt(j), we increment both i and j.
    • If not, we update j to the value in the prefix suffix array at index j-1.
    • If j reaches 0, we increment i.
  3. The result will be the substring from index 0 to the last index of the prefix suffix array.

Time Complexity: O(n) Space Complexity: O(n)

Solution Code

class Solution {
    public String longestPrefix(String s) {
        int n = s.length();
        int[] lps = new int[n];
        int j = 0;
        for (int i = 1; i < n; i++) {
            if (s.charAt(i) == s.charAt(j)) {
                lps[i] = ++j;
            } else {
                if (j != 0) {
                    j = lps[j - 1];
                    i--;
                }
            }
        }
        return s.substring(0, lps[n - 1]);
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 1392 (Longest Happy Prefix)?

This page provides optimized solutions for LeetCode problem 1392 (Longest Happy Prefix) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 1392 (Longest Happy Prefix)?

The time complexity for LeetCode 1392 (Longest Happy Prefix) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 1392 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1392 in Java, C++, or Python.

Back to LeetCode Solutions