Drill

ProblemsJava › data

Interleave two lists

easydataTwo pointersArraysJava

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

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

Java 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

List<Integer> alternatingMerge(List<Integer> first, List<Integer> second) {
    
}

Worked examples

CallResult
alternatingMerge(Main.<Integer>ls(1, 2, 3), Main.<Integer>ls(9))Main.<Integer>ls(1, 9, 2, 3)
alternatingMerge(Main.<Integer>ls(1), Main.<Integer>ls(4, 5))Main.<Integer>ls(1, 4, 5)
alternatingMerge(Main.<Integer>ls(1, 2), Main.<Integer>ls(3, 4))Main.<Integer>ls(1, 3, 2, 4)
alternatingMerge(Main.<Integer>ls(), Main.<Integer>ls(1, 2))Main.<Integer>ls(1, 2)

Hint

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

Reference solution in Java
List<Integer> alternatingMerge(List<Integer> first, List<Integer> second) {
    List<Integer> result = new ArrayList<>();
    int n = Math.max(first.size(), second.size());
    for (int i = 0; i < n; i++) {
        if (i < first.size()) result.add(first.get(i));
        if (i < second.size()) result.add(second.get(i));
    }
    return result;
}

The same problem in another language

More data problems in Java