Ctrl K

Trim Three Words Until They Match

Easy
You get three strings first, second and third. In one operation you pick any of them and delete its last character, but a string may never become empty. Return the fewest operations after which all three strings are equal, or -1 if that cannot be done.
Example 1
first='plant', second='plan', third='planet' → 3

Trim plant to plan (1 operation) and planet to plan (2 operations): 3 in total.

Example 2
first='sun', second='sun', third='sun' → 0

The strings already match.

Example 3
first='cat', second='cot', third='bat' → -1

The first letters differ and no string may be erased completely, so the answer is -1.

Constraints
  • 1 ≤ len(first), len(second), len(third) ≤ 100
  • The strings consist of lowercase English letters
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsValue of a Roman Numeral EasyShared Start of Words EasyBracket Balance EasyWhere the Fragment Starts EasyLength of the Final Word Easy
loading Python…
Input
first='plant', second='plan', third='planet'
Expected
3

Run checks the first 3 tests in your browser. Submit checks all 128 tests on the server, hidden ones included.