Ctrl K

Shortest String Holding Two Words

Hard
You are given two words, first and second. Find the shortest string from which each of them can be obtained by crossing out some characters (the remaining characters keep their order). There are usually several such strings, so the answer is pinned down by the following rule. The string is built from the end, one letter at a time, until both words are used up. At each step, look at the last unused letters of both words: 1. if the last letter of first can be placed (counting it for first only) and the result can still be as short as possible, place it; 2. otherwise, if the last letter of second can be placed that way (for second only), place it; 3. otherwise the last letters of the two words are equal: place that letter and count it for both words. Return the resulting string.
Example 1
first="cat", second="cut" → 'cuat'

The shared letters c and t are used once and only a and u remain, so the length is 4. Building from the end: t is shared by both words, then a from first, then u from second and the shared c. That gives cuat.

Example 2
first="ab", second="ba" → 'bab'

Both aba and bab work. The last letter can be the b of first, so the answer is bab.

Example 3
first="pine", second="pine" → 'pine'

The words are equal, and the word itself already contains both.

Constraints
  • 1 ≤ len(first), len(second) ≤ 1000
  • first and second consist of lowercase English letters
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsPattern With Dot and Star HardLongest Balanced Bracket Stretch HardDoes the Text Fit the Pattern HardShuffle by Cutting and Swapping HardWays to Cross Out Hard
loading Python…
Input
first="cat", second="cut"
Expected
'cuat'

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