oneby7

String Matching Pattern matching

583. Longest Happy Prefix

Hard

You are given a string s. Return its longest happy prefix, or the empty string if it has none.

A happy prefix is a prefix of s that is also a suffix of s and is shorter than s itself. A prefix is made of the first few letters of s, and a suffix is made of the last few. The prefix and the suffix may overlap inside s. The empty string does not count as a happy prefix.

Answers are shown in double quotes, so an empty answer shows as "".

Example 1

Input: s = "onionion"

Output: "onion"

Explanation: Both on and onion start and end s. The longer one is onion. Its two copies overlap: they share the letters on at indexes 3 and 4.

Example 2

Input: s = "abcd"

Output: ""

Explanation: Every prefix starts with a, but no suffix shorter than s does. So s has no happy prefix.

Example 3

Input: s = "zzzz"

Output: "zzz"

Explanation: The whole string does not count, so the longest happy prefix is zzz. Its two copies overlap in zz.

Check your understanding

Work out the answer for this input before you write any code.

s = "abababa"

Constraints

  • 1 ≤ s.length ≤ 105
  • s holds only lowercase English letters.

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.