Merge Strings Alternately

(#1768), Easy

Category: String, Two Pointer

Problem Statement

You are given two strings `word1` and `word2`. Merge the strings by adding letters in alternating order, starting with `word1`. If one string is longer than the other, append the additional letters at the end of the merged string. Return the merged string.

Examples

Input: word1 = "abc", word2 = "pqr"

Output: "apbqcr"

Explanation: Characters are alternated: a (from word1), p (from word2), b, q, c, r.

Input: word1 = "ab", word2 = "pqrs"

Output: "apbqrs"

Explanation: After alternating a-p, b-q, word2 has extra characters r and s which are appended.

Input: word1 = "abcd", word2 = "pq"

Output: "apbqcd"

Explanation: After alternating a-p, b-q, word1 has extra characters c and d which are appended.

Approach

Two Pointer Technique

  • Initialize two pointers `w1Index` and `w2Index` to 0.
  • While both pointers are within bounds of `word1` and `word2`, alternately append one character from each string to the result.
  • After the main loop, if there are any remaining characters in `word1` or `word2`, append them to the result string.
  • Return the final merged result string.
var mergeAlternately = function (word1, word2) {
  let w1Index = 0;
  let w2Index = 0;
  let s = "";

  while (w1Index < word1.length && w2Index < word2.length) {
    s += word1[w1Index++];
    s += word2[w2Index++];
  }

  while (w1Index < word1.length) {
    s += word1[w1Index++];
  }

  while (w2Index < word2.length) {
    s += word2[w2Index++];
  }

  return s;
};

Complexity

Time: O(n)

Space: O(1) (excluding output string)

Watch Explanation

📊 Presentation (PPT)

📥 Download PPT

📎 Resources