2937. Make Three Strings Equal LeetCode Solution
In this guide, you will get 2937. Make Three Strings Equal LeetCode Solution with the best time and space complexity. The solution to Make Three Strings Equal problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.
Table of Contents
- Problem Statement
- Complexity Analysis
- Make Three Strings Equal solution in C++
- Make Three Strings Equal solution in Java
- Make Three Strings Equal solution in Python
- Additional Resources
Problem Statement of Make Three Strings Equal
You are given three strings: s1, s2, and s3. In one operation you can choose one of these strings and delete its rightmost character. Note that you cannot completely empty a string.
Return the minimum number of operations required to make the strings equal. If it is impossible to make them equal, return -1.
Example 1:
Input: s1 = “abc”, s2 = “abb”, s3 = “ab”
Output: 2
Explanation: Deleting the rightmost character from both s1 and s2 will result in three equal strings.
Example 2:
Input: s1 = “dac”, s2 = “bac”, s3 = “cac”
Output: -1
Explanation: Since the first letters of s1 and s2 differ, they cannot be made equal.
Constraints:
1 <= s1.length, s2.length, s3.length <= 100
s1, s2 and s3 consist only of lowercase English letters.
Complexity Analysis
- Time Complexity: O(n)
- Space Complexity: O(1)
2937. Make Three Strings Equal LeetCode Solution in C++
class Solution {
public:
int findMinimumOperations(string s1, string s2, string s3) {
const int minLength = min({s1.length(), s2.length(), s3.length()});
int i = 0;
while (i < minLength && s1[i] == s2[i] && s2[i] == s3[i])
++i;
return i == 0 ? -1 : s1.length() + s2.length() + s3.length() - i * 3;
}
};
/* code provided by PROGIEZ */
2937. Make Three Strings Equal LeetCode Solution in Java
class Solution {
public int findMinimumOperations(String s1, String s2, String s3) {
final int minLength = Math.min(s1.length(), Math.min(s2.length(), s3.length()));
int i = 0;
while (i < minLength && s1.charAt(i) == s2.charAt(i) && s2.charAt(i) == s3.charAt(i))
++i;
return i == 0 ? -1 : s1.length() + s2.length() + s3.length() - i * 3;
}
}
// code provided by PROGIEZ
2937. Make Three Strings Equal LeetCode Solution in Python
class Solution:
def findMinimumOperations(self, s1: str, s2: str, s3: str) -> int:
minLength = min(map(len, [s1, s2, s3]))
i = 0
while i < minLength and s1[i] == s2[i] and s2[i] == s3[i]:
i += 1
return -1 if i == 0 else len(s1) + len(s2) + len(s3) - i * 3
# code by PROGIEZ
Additional Resources
- Explore all LeetCode problem solutions at Progiez here
- Explore all problems on LeetCode website here
Happy Coding! Keep following PROGIEZ for more updates and solutions.