#3598

Longest Common Prefix Between Adjacent Strings After Removals

Medium
ArrayStringHash MapArray
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)

Precompute the longest common prefixes for adjacent pairs. This allows quick access to LCP lengths after each removal without recalculating.

⚙️

Algorithm

3 steps
  1. 1Step 1: Precompute the longest common prefix lengths for all adjacent pairs in the original array.
  2. 2Step 2: For each index i, check the LCP of pairs that would be adjacent after removing words[i].
  3. 3Step 3: Store the maximum LCP length for each removal in the answer array.
solution.py17 lines
1def longestCommonPrefix(words):
2    def lcp(s1, s2):
3        count = 0
4        while count < min(len(s1), len(s2)) and s1[count] == s2[count]:
5            count += 1
6        return count
7    n = len(words)
8    lcp_pairs = [lcp(words[i], words[i + 1]) for i in range(n - 1)]
9    answer = []
10    for i in range(n):
11        if i == 0:
12            answer.append(lcp_pairs[1])
13        elif i == n - 1:
14            answer.append(lcp_pairs[n - 2])
15        else:
16            answer.append(max(lcp_pairs[i - 1], lcp_pairs[i]))
17    return answer

Complexity note: Precomputing LCPs takes O(n), and each removal check is O(1).

  • 1Adjacent pairs determine the common prefix length.
  • 2Precomputation can save time during repeated checks.

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