Make Three Strings Equal - Problem

You are given three strings: s1, s2, and s3. Your goal is to make all three strings identical by performing a series of operations.

In each operation, you can choose any one of the three strings and delete its rightmost character. However, there's an important constraint: you cannot completely empty a string.

Return the minimum number of operations required to make all three strings equal. If it's impossible to make them equal, return -1.

Example: If you have strings "abc", "ab", and "abcd", you can delete the last character from the first string (1 operation) and the last character from the third string (1 operation) to make all three equal to "ab". Total: 2 operations.

Input & Output

example_1.py โ€” Basic case
$ Input: s1 = "abc", s2 = "abb", s3 = "ab"
โ€บ Output: 2
๐Ÿ’ก Note: The longest common prefix is "ab". We need to remove 1 character from s1 ("c") and 1 character from s2 ("b"), totaling 2 operations.
example_2.py โ€” Equal length strings
$ Input: s1 = "abc", s2 = "abc", s3 = "abc"
โ€บ Output: 0
๐Ÿ’ก Note: All three strings are already equal, so no operations are needed.
example_3.py โ€” No common prefix
$ Input: s1 = "abc", s2 = "def", s3 = "ghi"
โ€บ Output: -1
๐Ÿ’ก Note: The strings have no common prefix, so it's impossible to make them equal by only removing characters from the right.

Constraints

  • 1 โ‰ค s1.length, s2.length, s3.length โ‰ค 100
  • s1, s2, and s3 consist of lowercase English letters only.
  • You cannot completely empty any string (each final string must have at least 1 character).

Visualization

Tap to expand
๐ŸŽฏ Paper Trimming VisualizationPaper 1: "ABCDEF"ABCDEFPaper 2: "ABC"ABCPaper 3: "ABCX"ABCXโœ‚๏ธ Cutting Planโ€ข Paper 1: Cut 3 characters ("DEF")โ€ข Paper 2: Cut 0 charactersโ€ข Paper 3: Cut 1 character ("X")๐ŸŽฏ Result: All papers will show "ABC" (4 total cuts)The longest common prefix determines the final result
Understanding the Visualization
1
Align papers
Line up the three papers and compare from left to right
2
Find common text
Identify the longest prefix where all papers have identical text
3
Mark cutting points
Mark where to cut each paper to achieve the common length
4
Count cuts
Sum up all the characters that need to be removed
Key Takeaway
๐ŸŽฏ Key Insight: The final equal string must be the longest common prefix of all three input strings, since we can only remove characters from the right end.
Asked in
Google 23 Amazon 18 Microsoft 15 Meta 12
24.7K Views
Medium Frequency
~12 min Avg. Time
842 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen