Drill

ProblemsGo › patterns

Merge two sorted queues

mediumpatternsTwo pointersArraysGo

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>

Go 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

func mergeSorted(first []int, second []int) []int {
	
}

Worked examples

CallResult
mergeSorted([]int{1, 2, 4}, []int{1, 3})[]int{1, 1, 2, 3, 4}
mergeSorted([]int{}, []int{1, 2})[]int{1, 2}
mergeSorted([]int{1, 2}, []int{})[]int{1, 2}
mergeSorted([]int{}, []int{})[]int{}

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 Go
func mergeSorted(first []int, second []int) []int {
	merged := []int{}
	i, j := 0, 0
	for i < len(first) && j < len(second) {
	    if first[i] <= second[j] {
	        merged = append(merged, first[i])
	        i++
	    } else {
	        merged = append(merged, second[j])
	        j++
	    }
	}
	merged = append(merged, first[i:]...)
	merged = append(merged, second[j:]...)
	return merged
}

The same problem in another language

More patterns problems in Go