Drill

ProblemsC# › data

Interleave two lists

easydataTwo pointersArraysC#

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

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

C# needs a compiler and Drill does not host one yet, so this page is the reference rather than an exercise: the problem, worked examples, and the solution in full. To type it out, the same problem runs in Python.

Solve it in Python →

Where you start

public List<int> AlternatingMerge(List<int> first, List<int> second) {
    
}

Worked examples

CallResult
AlternatingMerge(new List<int> { 1, 2, 3 }, new List<int> { 9 })new List<int> { 1, 9, 2, 3 }
AlternatingMerge(new List<int> { 1 }, new List<int> { 4, 5 })new List<int> { 1, 4, 5 }
AlternatingMerge(new List<int> { 1, 2 }, new List<int> { 3, 4 })new List<int> { 1, 3, 2, 4 }
AlternatingMerge(new List<int> { }, new List<int> { 1, 2 })new List<int> { 1, 2 }

Hint

Loop up to the longer length and take each element that still exists.

Reference solution in C#
public List<int> AlternatingMerge(List<int> first, List<int> second) {
    var result = new List<int>();
    int n = Math.Max(first.Count, second.Count);
    for (int i = 0; i < n; i++) {
        if (i < first.Count) result.Add(first[i]);
        if (i < second.Count) result.Add(second[i]);
    }
    return result;
}

The same problem in another language

More data problems in C#