Pattern: Two Pointers → parallel traversal / merge
Difficulty: Easy
Time: O(n + m) | Space: O(n + m) for the output
Problem
Combine two strings by taking letters in turn: word1[0], word2[0], word1[1], …
When one runs out, add the rest of the other.
Core idea
Zip while both have items, then add the tail.
- Loop while both sequences have elements → take one from each
- Loop ends when the shorter one runs out
- Add the leftover part of the longer one (the shorter one’s leftover is empty)
Code (TypeScript)
function mergeAlternately(word1: string, word2: string): string {
const res: string[] = [];
let i = 0;
while (i < word1.length && i < word2.length) {
res.push(word1[i], word2[i]);
i++;
}
return res.join("") + word1.slice(i) + word2.slice(i);
}Gotchas
- Lengths differ → always test: word1 longer, word2 longer, equal lengths
slice(i)past the end returns"", so it never throws- JS out-of-range index returns
undefined(no error), so the loop guard matters - Strings are immutable → build with an array +
join("")instead of+=
(V8 optimises+=, but the habit matters in Java/Python and in interviews)
Cues for Two Pointers
- Two sequences processed together (merge, compare, interleave)
- Sorted input + looking for a pair/target
- Comparing from both ends (palindrome, reverse)
- Changing an array in place (slow = write, fast = read)
- Brute force would be nested loops → two pointers often gives O(n)
Same template shows up in
- Merge Sorted Array (LC 88)
- Merge Two Sorted Lists (LC 21)
- Merge step of Merge Sort
- Is Subsequence (LC 392), which is next in LeetCode 75