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

Hiring now

Software engineer roles are open right now

landed applies to roles like these for you, on each company’s own site, with answers written for the role.

Get 5x interviews10 free auto-applies. No card.
  • Senior Software Engineer -.NET

    Tyler Technologies · Annapolis, Maryland

  • Software Development Engineer II

    SaaS Labs · Bengaluru, Karnataka, India

  • Advanced Software Engineer - Product Architect (Legal, Safety, and Risk)

    Metropolitan Transportation Authority · New York, NY

Or practice this question first

Next question