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
word1is non-empty, append the first character inword1tomergeand delete it fromword1. - If
word2is non-empty, append the first character inword2tomergeand delete it fromword2.
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
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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code