Merge Strings Alternately(#1768)

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

We use the **Two Pointer Technique** to merge characters alternately from two strings:

โ€ข 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.

This ensures the strings are merged alternately, with any extra characters from the longer word added at the end.

๐Ÿ’ป Code

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