#2937

Make Three Strings Equal

Easy
StringTwo PointersString Matching
LeetCode ↗

Approaches

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

Intuition

Time O(n)Space O(1)

The optimal approach focuses on finding the longest common prefix of the three strings. By identifying this prefix, we can directly calculate how many characters need to be deleted from each string to make them equal.

⚙️

Algorithm

3 steps
  1. 1Step 1: Find the length of the longest common prefix of the three strings.
  2. 2Step 2: Calculate the number of operations needed to delete characters from each string to reach this prefix.
  3. 3Step 3: Return the total number of operations.
solution.py12 lines
1# Full working Python code
2
3def min_operations_optimal(s1, s2, s3):
4    min_length = min(len(s1), len(s2), len(s3))
5    common_length = 0
6    while (common_length < min_length and 
7           s1[common_length] == s2[common_length] == s3[common_length]):
8        common_length += 1
9    return (len(s1) - common_length) + (len(s2) - common_length) + (len(s3) - common_length)
10
11# Example usage
12print(min_operations_optimal('abc', 'abb', 'ab'))

Complexity note: This complexity is efficient because we only traverse the strings once to find the common prefix, making it linear with respect to the length of the strings.

  • 1Finding the longest common prefix is crucial to minimizing operations.
  • 2If the first characters of the strings differ, they can never be made equal.

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