Two Pointers
Sorted data has another trick besides binary search: walk through it with two indexes that only ever move forward. Each step moves at least one of them, so the whole walk takes O(n) with no extra map or set.
Two sorted lists, side by side
Say you have two sorted lists and want them as one sorted list. Keep an index into each. The smallest value not taken yet is always at one of the two indexes, so take the smaller one and move that index on:
i, j := 0, 0
for i < len(a) && j < len(b) {
if a[i] <= b[j] {
out = append(out, a[i])
i++
} else {
out = append(out, b[j])
j++
}
}
out = append(out, a[i:]...) // whatever is left in one of them
out = append(out, b[j:]...)
When one list runs out, the rest of the other is already in order, so it's added as it is. This is the merge step that merge sort is built on.
The same walk finds the values two lists share: if a[i] == b[j], it's in both, so move both indexes; otherwise move the index at the smaller value, since that value can't appear later in the other list.
From both ends
The two indexes can also start at opposite ends of one sorted slice and walk towards each other. To find two values that add up to a target:
lo, hi := 0, len(xs)-1
for lo < hi {
sum := xs[lo] + xs[hi]
switch {
case sum == target:
return xs[lo], xs[hi]
case sum < target:
lo++ // need a bigger sum
default:
hi-- // need a smaller sum
}
}
In the Maps and Sets chapter, a map solved the same question for unsorted data. When the data is sorted anyway, two pointers need no extra memory.
Task
Two gates at a concert scan tickets. This lesson's input has the ticket numbers scanned at gate A, a blank line, then those scanned at gate B. Both lists are sorted.
- Complete
merge(a, b []int) []int: every value of both sorted slices in one sorted slice, duplicates included. - Complete
both(a, b []int) []int: the values that are inaand inb, in order. Neither slice has a value twice.