#2573

Find the String with LCP

Hard
ArrayStringDynamic ProgrammingGreedyUnion-FindMatrixDynamic ProgrammingGreedy Algorithms
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

We can leverage the LCP matrix to directly construct the string by determining character groups based on the LCP values, ensuring we maintain lexicographical order.

⚙️

Algorithm

5 steps
  1. 1Step 1: Initialize a character array of size n to store the result.
  2. 2Step 2: Assign characters based on the longest common prefix lengths, ensuring that the same characters are assigned to indices that require them to be equal.
  3. 3Step 3: Use a greedy approach to assign the smallest available character to each group of equal indices.
  4. 4Step 4: Validate the constructed string against the LCP matrix.
  5. 5Step 5: Return the constructed string or an empty string if validation fails.
solution.py28 lines
1# Full working Python code
2class Solution:
3    def findTheString(self, lcp):
4        n = len(lcp)
5        word = [''] * n
6        for i in range(n):
7            if word[i] == '':
8                word[i] = 'a'
9            for j in range(i + 1, n):
10                if lcp[i][j] > 0:
11                    word[j] = word[i]
12                elif lcp[i][j] == 0:
13                    word[j] = chr(ord(word[i]) + 1)
14        return ''.join(word) if self.isValid(word, lcp) else ''
15
16    def isValid(self, word, lcp):
17        n = len(word)
18        for i in range(n):
19            for j in range(n):
20                if self.lcp(word, i, j) != lcp[i][j]:
21                    return False
22        return True
23
24    def lcp(self, word, i, j):
25        count = 0
26        while i + count < len(word) and j + count < len(word) and word[i + count] == word[j + count]:
27            count += 1
28        return count

Complexity note: The time complexity is O(n) because we iterate through the LCP matrix only once to construct the string. The space complexity is O(n) due to the storage of the result string.

  • 1Understanding the LCP matrix is crucial for constructing the string correctly.
  • 2Character assignments must respect the constraints imposed by the LCP values.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.