Algo-Sim › String Algorithms

Longest Happy Prefix

Hard · String Algorithms · step through it in Java, Python and C++ on your own input

The longest prefix that is also a suffix is the last entry of KMP’s lps table, built in O(n) by reusing shorter borders.

Problem

A happy prefix of s is a non-empty prefix that is also a suffix of s, but is not the whole string. Return the longest happy prefix, or the empty string if there is none.

Constraints

Edge cases to test

Follow-up questions

How else can it be done?
Compare rolling hashes of each prefix and suffix: O(n) expected, with collision risk.
How do you find the shortest palindrome by adding characters in front?
Run this on s + "#" + reverse(s); the border is the longest palindromic prefix (LC 214).

Solution

Java

public String longestPrefix(String p) {
    int m = p.length();
    int[] lps = new int[m];
    for (int i = 1, len = 0; i < m; ) {
        if (p.charAt(i) == p.charAt(len)) lps[i++] = ++len;
        else if (len > 0) len = lps[len - 1];
        else lps[i++] = 0;
    }
    return p.substring(0, lps[m - 1]);
}

Python

def longest_prefix(p):
    m = len(p)
    lps = [0] * m
    i, length = 1, 0
    while i < m:
        if p[i] == p[length]:
            length += 1
            lps[i] = length
            i += 1
        elif length > 0:
            length = lps[length - 1]
        else:
            lps[i] = 0
            i += 1
    return p[:lps[m - 1]]

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    string longestPrefix(string &p) {
        int m = int(p.size());
        vector<int> lps = vector<int>(m);
        for (int i = 1, len = 0; i < m;) {
            if (p[i] == p[len])
                lps[i++] = ++len;
            else if (len > 0)
                len = lps[len - 1];
            else
                lps[i++] = 0;
        }
        return p.substr(0, (lps[m - 1]) - (0));
    }
};

More String Algorithms problems