DSA Factory
Free Strings lessonsStrings · Stage 2 · Two pointers on text · Step 4

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.

One from each: first string, then second, each round.
a = "ab", b = "pqrs"
a
a
b
b
p
q
r
s
out
a
i
1
j
0

Take one from a: 'a'. i moves on.

Move 1 of 5

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.

Don't stop early: the longer string's leftovers still go in.
In code
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)
Quick check

What is "ab" merged alternately with "pqrs"?

  1. Aapbqrs
  2. Bapbq
  3. Cpqrsab
Show the answer

apbqrs. a p b q, then "ab" is used up and r s follow.

Your problem

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.

Example
a = "abc", b = "pqr" → "apbqcr"

0 ≤ lengths ≤ 100,000

Solve it in your browserFree account, no card. Python, C++, Java or JavaScript, with hints if you get stuck, and your progress is saved.
Sign up free to solve