Largest Merge Of Two Strings - Problem

You are given two strings word1 and word2. You want to construct a string merge in the following way:

While either word1 or word2 are non-empty, choose one of the following options:

  • If word1 is non-empty, append the first character in word1 to merge and delete it from word1.
  • If word2 is non-empty, append the first character in word2 to merge and delete it from word2.

Return the lexicographically largest merge you can construct.

A string a is lexicographically larger than a string b (of the same length) if in the first position where a and b differ, a has a character strictly larger than the corresponding character in b.

Input & Output

Example 1 — Basic Case
$ Input: word1 = "cab", word2 = "ab"
Output: "cabab"
💡 Note: At each step: "cab" vs "ab" → choose 'c', then "ab" vs "ab" → choose 'a', then "b" vs "b" → choose 'a', append remaining "bb"
Example 2 — Equal Start
$ Input: word1 = "abcabc", word2 = "abdaba"
Output: "abdabacabcabc"
💡 Note: "abcabc" vs "abdaba" → "abdaba" is larger, so choose 'a' from word2. Continue comparing suffixes.
Example 3 — One Empty
$ Input: word1 = "a", word2 = "b"
Output: "ba"
💡 Note: "a" vs "b" → 'b' > 'a', so choose 'b' first, then append remaining 'a'

Constraints

  • 1 ≤ word1.length, word2.length ≤ 3000
  • word1 and word2 consist only of lowercase English letters

Visualization

Tap to expand
Largest Merge Of Two Stringsword1: "cab"word2: "ab"Greedy ChoiceCompare suffixesChoose largerResult: "cabab"Steps: c(ab > ab) → a(b = b) → b → a → b
Understanding the Visualization
1
Input
Two strings word1="cab" and word2="ab"
2
Process
At each step, compare remaining suffixes and choose optimally
3
Output
Lexicographically largest merge "cabab"
Key Takeaway
🎯 Key Insight: Always choose from the string with the lexicographically larger remaining suffix
Asked in
Google 25 Amazon 18 Microsoft 12
32.5K Views
Medium Frequency
~25 min Avg. Time
847 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