#1768

Merge Strings Alternately

Easy
Two PointersStringTwo PointersString Manipulation
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution uses two pointers to efficiently merge the strings in a single pass. This approach minimizes the number of concatenations by building the result in a list and then joining it at the end, which is more efficient than repeatedly concatenating strings.

⚙️

Algorithm

5 steps
  1. 1Step 1: Initialize an empty list to hold characters.
  2. 2Step 2: Use two pointers to iterate through both strings.
  3. 3Step 3: For each pointer, append the character from word1 and then from word2 to the list.
  4. 4Step 4: After the loop, append any remaining characters from either string to the list.
  5. 5Step 5: Join the list into a single string and return it.
solution.py10 lines
1def mergeAlternately(word1, word2):
2    result = []
3    i = 0
4    while i < len(word1) or i < len(word2):
5        if i < len(word1):
6            result.append(word1[i])
7        if i < len(word2):
8            result.append(word2[i])
9        i += 1
10    return ''.join(result)

Complexity note: This complexity is linear because we are iterating through both strings once, and the space complexity is also linear due to storing the result in a list before joining.

  • 1Using two pointers allows for efficient traversal of both strings.
  • 2Building the result with a list and joining it minimizes costly string concatenation operations.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.