Drill

ProblemsGo › data

Interleave two lists

easydataTwo pointersArraysGo

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

alternatingMerge(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 alternatingMerge(first []int, second []int) []int {
	
}

Worked examples

CallResult
alternatingMerge([]int{1, 2, 3}, []int{9})[]int{1, 9, 2, 3}
alternatingMerge([]int{1}, []int{4, 5})[]int{1, 4, 5}
alternatingMerge([]int{1, 2}, []int{3, 4})[]int{1, 3, 2, 4}
alternatingMerge([]int{}, []int{1, 2})[]int{1, 2}

Hint

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

Reference solution in Go
func alternatingMerge(first []int, second []int) []int {
	result := []int{}
	n := len(first)
	if len(second) > n {
		n = len(second)
	}
	for i := 0; i < n; i++ {
		if i < len(first) {
			result = append(result, first[i])
		}
		if i < len(second) {
			result = append(result, second[i])
		}
	}
	return result
}

The same problem in another language

More data problems in Go