LeetCode 2937: Make Three Strings Equal Solution

Master LeetCode problem 2937 (Make Three Strings Equal), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

2937. Make Three Strings Equal

Easy

Problem Explanation

Explanation:

To make three strings equal, we need to find the minimum number of operations required to delete characters from the right end of each string such that they become equal. We can approach this problem by iterating through the strings from right to left and comparing the characters at each position.

  1. If the characters at the current position in all three strings are equal, we move to the next position.
  2. If any two characters are different, we cannot make the strings equal, thus return -1.
  3. If we encounter the end of one of the strings while the other strings still have characters remaining, we need to delete the remaining characters in those strings to make them equal. This will require the minimum number of operations.

By following this approach, we can determine if it is possible to make the strings equal and calculate the minimum number of operations required.

  • Time complexity: O(n), where n is the length of the longest string among s1, s2, and s3.
  • Space complexity: O(1)

Solutions:

Solution Code

class Solution {
    public int makeEqual(String s1, String s2, String s3) {
        int i = s1.length() - 1, j = s2.length() - 1, k = s3.length() - 1;
        
        while (i >= 0 && j >= 0 && k >= 0) {
            if (s1.charAt(i) == s2.charAt(j) && s2.charAt(j) == s3.charAt(k)) {
                i--;
                j--;
                k--;
            } else {
                return -1;
            }
        }
        
        return s1.length() - i - 1 + s2.length() - j - 1 + s3.length() - k - 1;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 2937 (Make Three Strings Equal)?

This page provides optimized solutions for LeetCode problem 2937 (Make Three Strings Equal) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 2937 (Make Three Strings Equal)?

The time complexity for LeetCode 2937 (Make Three Strings Equal) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 2937 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2937 in Java, C++, or Python.

Back to LeetCode Solutions