Problem Description
Given three strings s1, s2, and s3, you are allowed to delete the rightmost character of any one of these strings in an operation (without completely emptying any string). The goal is to determine the minimum number of operations required to make all three strings equal. If making the strings equal is impossible, return -1.
Key Insights
- Only prefixes of the original strings can be achieved by deleting characters from the end.
- The target string must be a common prefix shared by s1, s2, and s3.
- Maximizing the length of this common prefix minimizes the number of deletions.
- The total operations required equals the sum of the differences between each string's length and the common prefix length.
- If there is no common prefix (of at least length 1), then it is impossible to make the strings equal.
Space and Time Complexity
Time Complexity: O(n) where n is the minimum length among s1, s2, and s3. Space Complexity: O(1)
Solution
The solution involves first calculating the length of the common prefix among all three strings. This is done by iterating from the start of the strings until a mismatch is encountered. Let l be the length of this common prefix. If l is greater than 0, then we can trim each string to its prefix of length l. The number of operations required is calculated as (len(s1) - l) + (len(s2) - l) + (len(s3) - l). If l is 0, it means there is no common starting character shared by all the strings, and the answer is -1. This approach uses simple iteration and arithmetic operations while ensuring O(1) space.