We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Largest Merge Of Two Strings

Number: 1880

Difficulty: Medium

Paid? No

Companies: Snap


Problem Description

Given two strings word1 and word2, construct a new string merge by repeatedly choosing and removing the first character from either word1 or word2. The goal is to form the lexicographically largest possible merge string.


Key Insights

  • Use a greedy approach by always comparing the remaining parts of word1 and word2.
  • At each step, choose the character from the string that is lexicographically larger (when comparing the whole remaining strings).
  • Continue until both strings are exhausted.

Space and Time Complexity

Time Complexity: O(m+n) average; in worst-case scenarios (such as repeated characters) comparisons can be more expensive, but it is acceptable for the given constraints. Space Complexity: O(m+n) for the merge string, where m and n are the lengths of word1 and word2.


Solution

The solution employs a greedy approach. Maintain the two given strings and, in each iteration, compare the remaining substrings word1 and word2. Append the first character of the lexicographically larger substring to the merge string and remove it from the selected word. This process continues until both strings are empty. This greedy decision is justified since making a locally optimal choice at each step leads to the globally optimal lexicographically largest merge.


Code Solutions

Below are line-by-line commented code solutions in Python, JavaScript, C++, and Java.

# Python solution using greedy approach.
def largestMerge(word1: str, word2: str) -> str:
    merge = []  # List to build the merge result efficiently.
    # Continue while there's still characters in either word1 or word2.
    while word1 or word2:
        # If word1 is greater than word2 lexicographically, choose first char of word1.
        if word1 > word2:
            merge.append(word1[0])
            word1 = word1[1:]  # Remove the chosen character.
        else:
            merge.append(word2[0])
            word2 = word2[1:]  # Remove the chosen character.
    return ''.join(merge)

# Example usage:
print(largestMerge("cabaa", "bcaaa"))
← Back to All Questions