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
LCP Matrix → String ReconstructionLCP Matrix[4,0,2,0][0,3,0,1][2,0,2,0][0,1,0,1]GreedyConstructionTry a,b,c..."abab"lcp[0][2] = 2: suffixes "abab" and "ab" share prefix "ab"Build lexicographically smallest string satisfying all LCP constraints
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
Asked in
Google 15 Microsoft 12 Amazon 8
8.5K Views
Medium Frequency
~35 min Avg. Time
234 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen