Longest happy prefix

Strings (Advanced Algo) Advanced Problems (Less asked) Hard

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 "".

Examples:

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"

Constraints

  • 1 <= s.length <= 104

Hints

  • "Compute the LPS Array: The LPS array for s stores the length of the longest prefix that is also a suffix for each prefix of s. The last value in LPS gives the length of the longest happy prefix."
  • Extract the happy prefix: If lps[-1] > 0, return s[:lps[-1]]. Otherwise, return """".

Company Tags

Wayfair Intel American Express Databricks Epic Games Western Digital Mastercard Etsy PayPal McKinsey & Company Dropbox Shopify Texas Instruments KPMG JPMorgan Chase Target ARM Red Hat Electronic Arts Philips Healthcare Rockstar Games Cloudflare Docker Square Reddit Google Microsoft Amazon Meta Apple Netflix Adobe