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 Strings INPUT word1: c a b word2: a b Input Values: word1 = "cab" word2 = "ab" Goal: Build lexicographically largest merge string ALGORITHM STEPS 1 Compare Strings "cab" > "ab" (c > a) Take 'c' from word1 2 Compare Again "ab" == "ab" Take 'a' from word1 3 Compare Strings "b" > "ab" (b > a) Take 'b' from word1 4 Append Remaining word1 empty, add "ab" from word2 Greedy Rule: Always pick from larger string FINAL RESULT Merged String: c a b a b from word1 from word2 Output: "cabab" OK - Verified! Lexicographically largest possible merge Trace: c-->a-->b-->a-->b Key Insight: When choosing which character to append, compare the ENTIRE remaining strings, not just the first characters. If word1 >= word2 lexicographically, take from word1; otherwise take from word2. This greedy choice is optimal. TutorialsPoint - Largest Merge Of Two Strings | Greedy Choice Approach
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