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
Find the String with LCP - Greedy Construction INPUT LCP Matrix (4x4): 0 1 2 3 0 4 0 2 0 1 0 3 0 1 2 2 0 2 0 3 0 1 0 1 Diagonal (length) Same char positions lcp[i][j] = common prefix length of word[i:] & word[j:] n = 4, lcp matrix given ALGORITHM STEPS 1 Initialize Start with char 'a' word = [?, ?, ?, ?] 2 Greedy Assign pos 0: assign 'a' lcp[0][2]>0 means same pos 2: also 'a' 3 Next Character pos 1: lcp[0][1]=0 different from 'a' assign 'b', pos 3='b' 4 Verify LCP Check constructed string matches matrix a b a b FINAL RESULT Constructed String: a 0 b 1 a 2 b 3 Verification: word[0:] = "abab" word[2:] = "ab" LCP = 2 [OK] word[1:] = "bab" word[3:] = "b" LCP = 1 [OK] word[0:] vs word[1:] LCP = 0 [OK] Output: "abab" Key Insight: If lcp[i][j] > 0, positions i and j must have the same character. Use Union-Find to group positions with same char, then greedily assign smallest available letter to each group. Finally verify: computed LCP of result must exactly match input matrix, else return "". TutorialsPoint - Find the String with LCP | Greedy Character Construction
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