Problem 1754

Abstract / Summary

Given two strings, repeatedly append the lexicographically smaller string or the first possible characters of both if equal, until one is empty, to form the largest possible merged string.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 1754.py

class Solution:
    def largestMerge(self, word1: str, word2: str) -> str:
        result = ""
        a = b = 0 # positions
        while a < len(word1) and b < len(word2):
            if word1[a:] > word2[b:]:
                result += word1[a]
                a += 1
            else:
                result += word2[b]
                b += 1

        return result + word1[a:] + word2[b:]
13 lines | 406 bytes | submitted January 6, 2024 | GitHub   8% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 54% (60k+ submissions).

Typical patterns to solve this problem:
  • Greedy
  • String
  • Two Pointers
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation defines a Solution class with a single method largestMerge. The method receives two strings, word1 and word2, and constructs a new string that is the lexicographically largest possible merge of the two inputs. The algorithm proceeds by iteratively selecting the next character from the string whose remaining suffix is greater in lexical order, appending that character to the result, and advancing the corresponding index. When one of the strings is exhausted, the remainder of the other string is appended directly.

Key Steps

The core logic is organized around three distinct phases: initialization, iterative selection, and final concatenation.

Initialization sets up the result container and index pointers for both input strings.

result = ""
a = b = 0  # positions

Iterative selection runs while both indices are within the bounds of their respective strings. At each iteration the code compares the remaining suffixes word1[a:] and word2[b:]. The comparison leverages Python’s built-in lexicographic ordering for strings, which evaluates characters sequentially and stops as soon as a difference is found. If the suffix of word1 is greater, the character at position a is taken; otherwise the character at position b is taken. The chosen character is appended to result, and the corresponding index is incremented.

while a < len(word1) and b < len(word2):
    if word1[a:] > word2[b:]:
        result += word1[a]
        a += 1
    else:
        result += word2[b]
        b += 1

Final concatenation occurs after the loop exits, meaning at least one of the strings has been fully consumed. The remaining portion of the non-exhausted string is appended to result in a single operation.

return result + word1[a:] + word2[b:]

Edge Cases Handled

The algorithm gracefully handles several boundary conditions without additional branching:

  • Both strings empty - The while loop condition fails immediately, and the final return concatenates two empty slices, yielding an empty string.
  • One string empty from the start - The loop never executes because one index already equals the length of its string. The return statement concatenates the empty slice with the full non-empty string, producing the original non-empty input.
  • Identical prefixes - When the current characters are equal, the suffix comparison determines which string offers a larger continuation. This ensures that the merge prefers the string that can produce a larger overall result, even when the immediate characters are the same.
  • Exhaustion of one string before the other - The loop stops as soon as either a reaches len(word1) or b reaches len(word2). The remaining characters of the other string are appended unchanged, preserving their original order.

Performance Optimizations Observed

The implementation makes use of Python’s native string slicing and comparison mechanisms, which are highly optimized in the interpreter. By comparing whole suffixes (word1[a:] vs. word2[b:]) rather than iterating character by character, the code benefits from early termination of the comparison as soon as a decisive character is found. This reduces the amount of work required for strings that diverge early in their suffixes.

Appending a single character to result inside the loop is performed with the += operator. While repeated concatenation can be costly for very large strings, the algorithm’s design ensures that each character is added exactly once, and the final concatenation of the remaining slices occurs in a single step, minimizing the number of intermediate string creations.

The use of simple integer indices (a and b) avoids the overhead of more complex data structures, keeping the per-iteration work lightweight. The loop condition checks both lengths directly, allowing the interpreter to short-circuit as soon as one string is depleted.

written by openai gpt

ELI5 - Simplified Explanation

Imagine there are two separate piles of alphabet blocks, and each pile spells out a word. The goal is to build one super long word by taking one block at a time from the front of either pile. To make the best word, the computer looks at both piles and compares them to see which one starts with a letter that comes later in the alphabet. If a letter appears later in the alphabet, it gets moved to the new pile first because that makes the final word start with bigger letters.

The computer keeps checking the very front blocks of both piles over and over again. It picks the winner, puts that block into the new super word, and moves to the next block in that pile. This continues until one of the piles runs out of blocks. Once one pile is empty, the computer just gathers up whatever is left in the other pile and pops them all onto the end of the new word. Everything is finished once all the blocks from both piles are safely tucked away in the single, brand new word.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 7 | μ = 7.22 | σ = 1.37

Complexity Analysis

not analyzed yet

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python Java C Go Rust TS
Progiez C++ Python Java
github black-shadows C++
charles-wangkai Java
everthis JS
fsq C++
haoel C++
JoshCrozier JS
lkwq007 Python
suxrobGM C#
wisdompeak C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C, C++, Go, Java, Python, Rust, TypeScript
Progiez C++, Java, Python
black-shadows C++, C++
charles-wangkai Java
everthis JavaScript
fsq C++
haoel C++
JoshCrozier JavaScript
lkwq007 Python
suxrobGM C#
wisdompeak C++
26 links | 13 authors | 9 languages

Videos

3 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

10 solutions   January 6, 2024

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality