Interleave two lists
Two queues for two registers are interleaved so every other customer comes from each.
- Take one from the first list, then one from the second, and so on.
- When one list runs out, append whatever remains of the other.
alternating_merge(first: list<int>, second: list<int>) → list<int>
Where you start
def alternating_merge(first: list[int], second: list[int]) -> list[int]:
Worked examples
| Call | Result |
|---|---|
alternating_merge([1, 2, 3], [9]) | [1, 9, 2, 3] |
alternating_merge([1], [4, 5]) | [1, 4, 5] |
alternating_merge([1, 2], [3, 4]) | [1, 3, 2, 4] |
alternating_merge([], [1, 2]) | [1, 2] |
Hint
Loop up to the longer length and take each element that still exists.
Reference solution in Python
def alternating_merge(first: list[int], second: list[int]) -> list[int]:
result = []
n = max(len(first), len(second))
for i in range(n):
if i < len(first):
result.append(first[i])
if i < len(second):
result.append(second[i])
return result