Make Three Strings Equal — LeetCode 2937 Python Solution

EasyString
Problem
#2937
Pattern
Hash Map
Reading time
2 min

The problem

You are given three strings: s1, s2, and s3. In one operation you can choose one of these strings and delete its rightmost character.

Python solution

Python
class Solution:
    def findMinimumOperations(self, s1: str, s2: str, s3: str) -> int:
        s = len(s1) + len(s2) + len(s3)
        n = min(len(s1), len(s2), len(s3))
        for i in range(n):
            if not s1[i] == s2[i] == s3[i]:
                return -1 if i == 0 else s - 3 * i
        return s - 3 * n

Complexity

MeasureComplexity
TimeO(n), where n is the minimum length of the three strings
SpaceO(1) auxiliary

Pattern: Hash Map

Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 2937. Make Three Strings Equal is filed here because the reference solution below belongs to the algorithm family this hub collects, even though its LeetCode tags point elsewhere.

The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2937. Make Three Strings Equal?
LeetCode 2937. Make Three Strings Equal is rated Easy on LeetCode.
What is the time complexity of LeetCode 2937. Make Three Strings Equal?
The Python solution on this page runs in O(n), where n is the minimum length of the three strings.
What is the space complexity of LeetCode 2937. Make Three Strings Equal?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 2937. Make Three Strings Equal cover?
LeetCode 2937. Make Three Strings Equal is tagged String on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview