Find the String with LCP — LeetCode 2573 Python Solution

HardGreedyUnion FindArrayStringDynamic ProgrammingMatrix
Problem
#2573
Pattern
Union-Find
Reading time
5 min

The problem

We define the lcp matrix of any 0-indexed string word of n lowercase English letters as an n x n grid such that: lcp[i][j] is equal to the length of the longest common prefix between the substrings word[i,n-1] and word[j,n-1]. Given an n x n matrix lcp, return the alphabetically smallest string word that corresponds to lcp.

Example

Input
lcp = [[4,0,2,0],[0,3,0,1],[2,0,2,0],[0,1,0,1]]
Output
"abab"
Explanation
lcp corresponds to any 4 letter string with two alternating letters. The lexicographically smallest of them is "abab".

Python solution

Python
class Solution:
    def findTheString(self, lcp: List[List[int]]) -> str:
        n = len(lcp)
        s = [""] * n
        i = 0
        for c in ascii_lowercase:
            while i < n and s[i]:
                i += 1
            if i == n:
                break
            for j in range(i, n):
                if lcp[i][j]:
                    s[j] = c
        if "" in s:
            return ""
        for i in range(n - 1, -1, -1):
            for j in range(n - 1, -1, -1):
                if s[i] == s[j]:
                    if i == n - 1 or j == n - 1:
                        if lcp[i][j] != 1:
                            return ""
                    elif lcp[i][j] != lcp[i + 1][j + 1] + 1:
                        return ""
                elif lcp[i][j]:
                    return ""
        return "".join(s)

Complexity

MeasureComplexity
TimeO(n^2)
SpaceO(n) auxiliary

Pattern: Union-Find

Merge groups and ask whether two things are connected, both in near-constant time. LeetCode 2573. Find the String with LCP is filed here because LeetCode tags it Union Find, which is the vocabulary this hub collects.

The union-find guide has the Python template for the pattern and the 83 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2573. Find the String with LCP?
LeetCode 2573. Find the String with LCP is rated Hard on LeetCode.
What is the time complexity of LeetCode 2573. Find the String with LCP?
The Python solution on this page runs in O(n^2).
What is the space complexity of LeetCode 2573. Find the String with LCP?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 2573. Find the String with LCP cover?
LeetCode 2573. Find the String with LCP is tagged Greedy, Union Find, Array, String, Dynamic Programming and Matrix on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview