You're given two strings word1 and word2, and your task is to create the lexicographically largest merged string possible by following specific merging rules.
Merging Rules:
- While either string is non-empty, you must choose one of these operations:
- Option 1: Take the first character from
word1, append it to your result, and remove it fromword1 - Option 2: Take the first character from
word2, append it to your result, and remove it fromword2
Goal: Make the smartest choices to create the lexicographically largest possible merge.
Remember: A string is lexicographically larger if at the first differing position, it has a character that comes later in the alphabet.
Example: If word1 = "cab" and word2 = "dab", the optimal merge is "dcabab" because we greedily pick 'd' first (largest available), then 'c', then 'a', then 'b', then 'a', then 'b'.
Input & Output
Visualization
Time & Space Complexity
We iterate through both strings once, but suffix comparison in worst case takes O(min(m,n)) time
Only space needed is for the result string of length m+n
Constraints
- 1 โค word1.length, word2.length โค 3000
- word1 and word2 consist only of lowercase English letters
- The merged string will have length exactly word1.length + word2.length