Problem Description
Given an n x n lcp matrix, where lcp[i][j] equals the length of the longest common prefix between the suffixes word[i:] and word[j:], return the lexicographically smallest string "word" (composed of lowercase English letters) that produces this matrix. If no such word exists, return an empty string.
Key Insights
- The diagonal lcp[i][i] must equal the length of the suffix starting at i (i.e. n - i).
- A positive lcp[i][j] implies that the first character of word[i] and word[j] must be the same.
- Characters at positions beyond the common prefix must differ if the lcp value is less than the available length.
- The constraints imply equality relationships between different positions that can be captured using union-find.
- To achieve the lexicographically smallest result, assign the smallest possible available letter to each equivalence class.
- After constructing a candidate string, validate it against the provided lcp matrix.
Space and Time Complexity
Time Complexity: O(n^2) due to the nested loops for unioning, grouping, and validating the lcp for each pair. Space Complexity: O(n) for the union-find structure, with additional O(n^2) for iterating over the lcp matrix in the worst-case.
Solution
We first validate the diagonal conditions (i.e. lcp[i][i] == n - i). Then, using a union-find (disjoint set) structure, we union indices that must carry the same character when lcp[i][j] > 0. After forming these groups, we ensure that the number of distinct groups does not exceed 26 (the total number of lowercase letters). We then assign letters to each group in order of their smallest index to achieve the lexicographically smallest answer. Finally, we validate that the constructed candidate string matches the lcp matrix, returning the string if valid, or an empty string otherwise.