Difficulty: Easy | Acceptance: 44.90% | Paid: No Topics: String
You are given three strings s1, s2, and s3 of the same length.
In one operation, you can choose one of the strings and delete its rightmost character.
Return the minimum number of operations required to make the strings equal. If it is impossible to make them equal, return -1.
- Examples
- Constraints
- Iterative Approach
- While Loop Approach
Examples
Input: s1 = "abc", s2 = "abb", s3 = "ab"
Output: 2
Explanation: Delete the rightmost character from s1 and s2 to get "ab" and "ab".
Input: s1 = "dac", s2 = "bac", s3 = "cac"
Output: -1
Explanation: The first characters of all strings are different, so it's impossible.
Constraints
1 <= s1.length, s2.length, s3.length <= 100
s1, s2, and s3 consist only of lowercase English letters.
Iterative Approach
Intuition Since we can only delete from the end, the resulting string must be a common prefix of all three strings. We find the longest common prefix and calculate deletions needed.
Steps
- Check if first characters match; if not, return -1
- Iterate through characters while all three match
- Calculate total operations as sum of (length - common_length)
python
class Solution:
def findMinimumOperations(self, s1: str, s2: str, s3: str) -> int:
if not s1 or not s2 or not s3:
return -1
if s1[0] != s2[0] or s2[0] != s3[0]:
return -1
common = 0
min_len = min(len(s1), len(s2), len(s3))
for i in range(min_len):
if s1[i] == s2[i] == s3[i]:
common += 1
else:
break
return (len(s1) - common) + (len(s2) - common) + (len(s3) - common)Complexity
- Time: O(n) where n is the length of the shortest string
- Space: O(1)
- Notes: Simple and efficient, single pass through the strings
While Loop Approach
Intuition Same logic as the iterative approach, but using a while loop for cleaner index-based iteration.
Steps
- Check if first characters match; if not, return -1
- Use while loop to find matching prefix length
- Calculate total operations as sum of (length - common_length)
python
class Solution:
def findMinimumOperations(self, s1: str, s2: str, s3: str) -> int:
if not s1 or not s2 or not s3:
return -1
if s1[0] != s2[0] or s2[0] != s3[0]:
return -1
i = 0
min_len = min(len(s1), len(s2), len(s3))
while i < min_len and s1[i] == s2[i] == s3[i]:
i += 1
return (len(s1) - i) + (len(s2) - i) + (len(s3) - i)Complexity
- Time: O(n) where n is the length of the shortest string
- Space: O(1)
- Notes: Same efficiency as for loop, slightly different style