Problem 2937

Abstract / Summary

You can make three strings equal by deleting characters so all become the same longest possible common string.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 2937.py

class Solution:
    def findMinimumOperations(self, s1: str, s2: str, s3: str) -> int:
        # stop markers
        s1 += "#"
        s2 += "?"
        s3 += "!"

        # find length of common prefix
        for i in range(min(len(s1), len(s2), len(s3))):
            if s1[i] != s2[i] or s2[i] != s3[i]:
                break

        # minus one to remove the stop markers
        return -1 if i == 0 else (len(s1) - i - 1) + (len(s2) - i - 1) + (len(s3) - i - 1)
14 lines | 484 bytes | submitted December 5, 2023 | GitHub   44% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 45% (90k+ submissions).

Typical patterns to solve this problem:
  • String
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The implementation computes the minimum number of character deletions required to make three input strings identical by trimming their suffixes. It does this by locating the longest common prefix among the three strings and then summing the characters that lie beyond that prefix in each string. The algorithm is linear in the length of the shortest string and uses only constant extra space.

Adding Stop Markers

s1 += "#"
s2 += "?"
s3 += "!"

Appending distinct sentinel characters to each string guarantees that the subsequent loop will always encounter a mismatch before reaching the end of any string. This eliminates the need for explicit bounds checking inside the loop and prevents an out-of-range access when the strings are identical up to their original lengths.

Determining the Common Prefix Length

for i in range(min(len(s1), len(s2), len(s3))):
    if s1[i] != s2[i] or s2[i] != s3[i]:
        break

The loop iterates up to the length of the shortest augmented string. At each position it compares the three characters; the moment any pair differs, the loop exits, leaving i as the index of the first mismatching character. Because the sentinel characters are all different, the loop will always break, ensuring i is defined after the loop finishes.

Computing the Result

return -1 if i == 0 else (len(s1) - i - 1) + (len(s2) - i - 1) + (len(s3) - i - 1)

If the first characters already differ (i == 0), the function returns -1 to signal that no common prefix exists. Otherwise, it subtracts the length of the common prefix (including the sentinel) from each original string length and adds the three remainders. The subtraction of one removes the sentinel that was added earlier, yielding the exact count of characters that must be removed from each string.

Edge Cases Handled

When any input string is empty, the sentinel ensures the loop still executes at least once, resulting in i == 0 and a return value of -1. This correctly reflects the impossibility of forming a common prefix.

If one string is a prefix of another (for example, "abc" and "abcd"), the sentinel placed after the shorter string causes the mismatch at the position immediately following the shorter string. The computed i equals the length of the shorter original string, and the formula correctly counts the extra characters in the longer strings.

When all three strings are identical, the sentinel characters differ, so the loop stops at the first sentinel position. The value of i equals the original length of the strings, and the final expression evaluates to zero, indicating that no deletions are required.

Performance Optimizations

The algorithm uses a single pass over the characters up to the length of the shortest string, avoiding multiple scans or nested loops. By employing the sentinel technique, it removes the need for separate end-of-string checks inside the loop, which reduces branch overhead. The use of min(len(s1), len(s2), len(s3)) ensures the loop never iterates beyond the necessary bound, keeping the execution time proportional to the actual amount of data examined. All calculations after the loop are simple arithmetic operations, contributing negligible overhead.

written by openai gpt

ELI5 - Simplified Explanation

Imagine three long towers made of colorful blocks. Each tower is a string of letters. Sometimes these towers look the same at the very bottom, and sometimes they start differently.

First, the code places a special, unique sticker at the top of each tower. One gets a hash sign, one gets a question mark, and one gets an exclamation point. These stickers act like stop signs to make sure the computer knows exactly when to stop looking.

Then, the code starts at the very bottom level and looks at the letters in all three towers at the same time. It checks if the letters match. If the letter in the first tower is the same as the letter in the second tower, and the same as the letter in the third tower, it moves up to the next level. It keeps climbing up together as long as the letters stay exactly the same.

The moment the letters stop matching, the computer stops climbing. It has found the tallest part where all three towers are twins.

Finally, the code counts all the extra blocks that are sitting on top of that common part in all three towers. It adds those extra blocks together to see how many would need to be taken away to make all three towers look exactly the same height at the bottom. If there were no matching blocks at all from the start, the computer remembers that result.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 4 | μ = 4.81 | σ = 1.91

Complexity Analysis

Time: linear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster Java C++ Python TS
WalkCCC Java C++ Python
leetcode.ca Java C++ Go Python TS
Progiez Java C++ Python
github charles-wangkai Java
everthis JS
fsq C++
JoshCrozier JS
varunu28 Java
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python, TypeScript
Progiez C++, Java, Python
charles-wangkai Java
everthis JavaScript
fsq C++
JoshCrozier JavaScript
varunu28 Java
20 links | 9 authors | 6 languages

Videos

6 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

10 solutions   December 5, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality