Skip to main content
Back to problems
#1754
Medium Algorithms

Largest merge of two strings

Two Pointers String Greedy
53.5% acceptance
Feb 25, 2026
612
87
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.

Solution

Rust
Time O(n)
Space O(n)
LeetCode
solution.rs
impl Solution {
  pub fn largest_merge(word1: String, word2: String) -> String {
    let w1 = word1.as_bytes();
    let w2 = word2.as_bytes();
    let mut i = 0;
    let mut j = 0;
    let mut result = Vec::with_capacity(w1.len() + w2.len());
    while i < w1.len() && j < w2.len() {
      if w1[i..] >= w2[j..] {
        result.push(w1[i]); i += 1;
      } else {
        result.push(w2[j]); j += 1;
      }
    }
    result.extend_from_slice(&w1[i..]);
    result.extend_from_slice(&w2[j..]);
    String::from_utf8(result).unwrap()
  }
}