Drill

ProblemsJava › patterns

Merge two sorted queues

mediumpatternsTwo pointersArraysJava

A worker pulls from two queues that are each already sorted, and must hand downstream one combined sorted stream.

mergeSorted(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> mergeSorted(List<Integer> first, List<Integer> second) {
    
}

Worked examples

CallResult
mergeSorted(Main.<Integer>ls(1, 2, 4), Main.<Integer>ls(1, 3))Main.<Integer>ls(1, 1, 2, 3, 4)
mergeSorted(Main.<Integer>ls(), Main.<Integer>ls(1, 2))Main.<Integer>ls(1, 2)
mergeSorted(Main.<Integer>ls(1, 2), Main.<Integer>ls())Main.<Integer>ls(1, 2)
mergeSorted(Main.<Integer>ls(), Main.<Integer>ls())Main.<Integer>ls()

Hint

Two pointers, one for each list. Take the smaller head, advance that pointer, and when one side runs out the rest of the other side follows.

Reference solution in Java
List<Integer> mergeSorted(List<Integer> first, List<Integer> second) {
    List<Integer> merged = new ArrayList<>();
    int i = 0, j = 0;
    while (i < first.size() && j < second.size()) {
        if (first.get(i) <= second.get(j)) merged.add(first.get(i++));
        else merged.add(second.get(j++));
    }
    while (i < first.size()) merged.add(first.get(i++));
    while (j < second.size()) merged.add(second.get(j++));
    return merged;
}

The same problem in another language

More patterns problems in Java