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.
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.
Where you start
public List<int> AlternatingMerge(List<int> first, List<int> second) {
}
Worked examples
| Call | Result |
|---|---|
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;
}