Two strings, two pointers
Weave two strings together, one character from each in turn. About 6 minutes.
Taking turns
Two friends take turns reading a sentence, one word each. Here it's letters: one from the first string, one from the second, one from the first again, and so on.
Give each string its own finger. Each round, take the letter under the first finger (if there is one) and then the letter under the second (if there is one), moving each finger along as you go.
- i
- 1
- j
- 0
Take one from a: 'a'. i moves on.
The longer one finishes alone
When one string runs out, don't stop. Keep going with just the other one, so its remaining letters are added in order. "ab" and "pqrs" give "apbqrs".
The easy mistake is stopping as soon as the shorter string ends. Check each finger against its own string's length.
out = []
i = j = 0
while i < len(a) or j < len(b):
if i < len(a):
out.append(a[i])
i += 1
if j < len(b):
out.append(b[j])
j += 1
return "".join(out)What is "ab" merged alternately with "pqrs"?
- Aapbqrs
- Bapbq
- Cpqrsab
Show the answer
apbqrs. a p b q, then "ab" is used up and r s follow.
Merge alternately
You get two strings a and b. Build a new string by taking a character from a, then one from b, and so on. When one string runs out, add the rest of the other. Return the result.
a = "abc", b = "pqr" → "apbqcr"
0 ≤ lengths ≤ 100,000