Find the String with LCP - 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. If there is no such string, return an empty string.
A string a is lexicographically smaller than a string b (of the same length) if in the first position where a and b differ, string a has a letter that appears earlier in the alphabet than the corresponding letter in b.
Input & Output
Example 1 — Basic Case
$
Input:
lcp = [[4,0,2,0],[0,3,0,1],[2,0,2,0],[0,1,0,1]]
›
Output:
abab
💡 Note:
The LCP matrix corresponds to the string 'abab'. lcp[0][2] = 2 because substrings 'abab' and 'ab' share 'ab' as prefix.
Example 2 — Single Character
$
Input:
lcp = [[1]]
›
Output:
a
💡 Note:
For a single character, lcp[0][0] = 1 means the suffix has length 1, so the string is 'a'.
Example 3 — Impossible Case
$
Input:
lcp = [[3,3],[3,3]]
›
Output:
💡 Note:
This matrix is impossible because lcp[0][1] = 3 but there are only 2 characters, so max LCP should be 2.
Constraints
- 1 ≤ lcp.length ≤ 1000
- lcp[i].length == lcp.length
- 0 ≤ lcp[i][j] ≤ lcp.length
Visualization
Tap to expand
Understanding the Visualization
1
Input
LCP matrix showing longest common prefixes between suffixes
2
Process
Build string character by character using constraints
3
Output
Lexicographically smallest string that produces the LCP matrix
Key Takeaway
🎯 Key Insight: Use LCP constraints to guide greedy character selection, ensuring the lexicographically smallest valid string
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code