Logo for ammarahmed.ca
Easy
Jan 25, 2026
#two-pointers

1768. Merge Strings Alternately

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

Return the merged string.

Example 1:

1Input: word1 = "abc", word2 = "pqr" 2Output: "apbqcr" 3Explanation: The merged string will be merged as so: 4word1: a b c 5word2: p q r 6merged: a p b q c r

Example 2:

1Input: word1 = "ab", word2 = "pqrs" 2Output: "apbqrs" 3Explanation: Notice that as word2 is longer, "rs" is appended to the end. 4word1: a b 5word2: p q r s 6merged: a p b q r s

Example 3:

1Input: word1 = "abcd", word2 = "pq" 2Output: "apbqcd" 3Explanation: Notice that as word1 is longer, "cd" is appended to the end. 4word1: a b c d 5word2: p q 6merged: a p b q c d
  • 1 <= word1.length, word2.length <= 100
    • word1 and word2 consist of lowercase English letters.

      Constraints:

      Notes

      Intuition

      The merge pattern alternates between strings: first character from word1, then word2, then word1, and so on. When one string is exhausted, append the remainder of the other.

      Implementation

      Use two pointers (i, j) for each word and a counter k to track whose turn it is. While both pointers are in bounds, add from word1 when k is even, from word2 when odd, incrementing the respective pointer. After the main loop, append any remaining characters from whichever string isn't exhausted.

      Edge-cases

      Strings of unequal length are handled by the trailing loops that append leftover characters. Empty strings work naturally—the main loop won't execute.

      • Time: O(n + m) — each character processed once
        • Space: O(1) — excluding the output string

          Complexity

          Solution

          1from typing import List 2 3class Solution: 4 def mergeAlternately(self, word1: str, word2: str) -> str: 5 i = j = k = 0 6 7 res = "" 8 while i < len(word1) and j < len(word2): 9 if k % 2 == 0: 10 res += word1[i] 11 i += 1 12 else: 13 res += word2[j] 14 j += 1 15 k += 1 16 17 while i < len(word1): 18 res += word1[i] 19 i += 1 20 21 while j < len(word2): 22 res += word2[j] 23 j += 1 24 25 return res 26 27 28if __name__ == "__main__": 29 # Include one-off tests here or debugging logic that can be run by running this file 30 # e.g. print(solution.two_sum([1, 2, 3, 4], 3)) 31 solution = Solution() 32