Make Three Strings Equal - 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.

Note: 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.

Input & Output

Example 1 — Basic Case
$ Input: s1 = "abc", s2 = "abcd", s3 = "ab"
Output: 3
💡 Note: The longest common prefix is "ab". Remove 1 character from s1, 2 from s2, and 0 from s3. Total: 1 + 2 + 0 = 3 operations.
Example 2 — No Common Prefix
$ Input: s1 = "abc", s2 = "def", s3 = "ghi"
Output: -1
💡 Note: No common prefix exists, so it's impossible to make them equal.
Example 3 — Already Equal
$ Input: s1 = "test", s2 = "test", s3 = "test"
Output: 0
💡 Note: All strings are already equal, so no operations are needed.

Constraints

  • 1 ≤ s1.length, s2.length, s3.length ≤ 100
  • s1, s2, and s3 consist only of lowercase English letters

Visualization

Tap to expand
Make Three Strings Equal INPUT s1 = "abc" a b c s2 = "abcd" a b c d s3 = "ab" a b Lengths: 3, 4, 2 Min length: 2 Find common prefix ALGORITHM STEPS 1 Check First Chars s1[0]=a, s2[0]=a, s3[0]=a All match - OK 2 Find Common Prefix i=0: a=a=a (match) i=1: b=b=b (match) Prefix length = 2 3 Count Deletions s1: 3-2 = 1 deletion s2: 4-2 = 2 deletions s3: 2-2 = 0 deletions 4 Calculate Total Total = 1 + 2 + 0 = (3+4+2) - 3*2 ops = len1+len2+len3 - 3*prefix ops = 3 + 4 + 2 - 3*2 = 3 FINAL RESULT Deletions Visualized: s1: "abc" --> "ab" a b c s2: "abcd" --> "ab" a b c d s3: "ab" --> "ab" (no change) a b Output: 3 Key Insight: We can only delete from the right, so all three strings must share a common prefix. Find the longest common prefix, then delete all characters after it from each string. If first characters differ, return -1 (impossible). Time: O(min length), Space: O(1). TutorialsPoint - Make Three Strings Equal | Optimized Single Pass
Asked in
Google 15 Amazon 12 Microsoft 8
8.5K Views
Medium Frequency
~10 min Avg. Time
340 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