Drill

ProblemsPython › data

Interleave two lists

easydataPython

Two queues for two registers are interleaved so every other customer comes from each.

alternating_merge(first: list<int>, second: list<int>) → list<int>

Solve it in the editor →

Where you start

def alternating_merge(first: list[int], second: list[int]) -> list[int]:
    

Worked examples

CallResult
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

The same problem in another language

More data problems in Python