Longest happy prefix

Asked atMicrosoft
1Give yourself 5 minutes
2Answer out loud, not in your head
3Then compare with the answer below

The problem

Given a string s, return the longest happy prefix of s. A happy prefix is a string that is both a proper prefix and a proper suffix.

If no such prefix exists, return an empty string "".

Input: s = "ababab"

Output: "abab"

Explanation: "abab" is the longest prefix which is also suffix. They can overlap in the original string.

Input: s = "aaaa"

Output: "aaa"

Explanation: "aaa" is the longest prefix which is also a suffix in the string "aaaa".

Input: s = "abc"

  • 1 <= s.length <= 104

cpp

class Solution{
  public:		
	string lps(string s) {
	
	}
};

java

class Solution {
    public String lps(String s) {
      
    }
}

python

class Solution:
    def lps(self, s: str) -> str:

javascript

class Solution {
    lps(s) {
   
    }
}

csharp

class Solution {
    public string Lps(string s) {

    }
}

go

func LPS(str string) string {
    // Implement your logic here
}
Stuck? Show a way to structure it+
  1. 01Build the prefix-function array.
  2. 02At each index, fall back through prior prefix lengths on mismatch.
  3. 03Extend the current border on a match.
  4. 04Read the final prefix value.
  5. 05Return that length from the start of the string.

Reference answer

Then expect these follow-ups

  • How can rolling hashes solve this probabilistically?

    Tests: follow-up reasoning

  • What is the relation between pi and the Z-function?

    Tests: follow-up reasoning

Free to read · better with Enzo

Practice this out loud with Enzo

Enzo runs it as a mock interview, pushes back with follow-ups, and grades you on the rubric.

Next question