Problem Solving with Go course

Sorting and SearchingTwo Pointers

Problem Solving with Go

Display

Theme

Sorting and Searching · Test exercise

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.

  1. Complete merge(a, b []int) []int: every value of both sorted slices in one sorted slice, duplicates included.
  2. Complete both(a, b []int) []int: the values that are in a and in b, in order. Neither slice has a value twice.
main.go
package main

import (
	"fmt"
	"io"
	"os"
	"strconv"
	"strings"
)

// merge returns every value of the sorted slices a and b in one sorted slice.
func merge(a, b []int) []int {
	// TODO: one index into a, one into b; always take the smaller value
	return nil
}

// both returns the values found in a and in b, in order. a and b are sorted and
// neither has a value twice.
func both(a, b []int) []int {
	// TODO: move whichever index points at the smaller value
	return nil
}

// numbers reads one number per line.
func numbers(block string) []int {
	var out []int
	for _, line := range strings.Fields(block) {
		n, err := strconv.Atoi(line)
		if err == nil {
			out = append(out, n)
		}
	}
	return out
}

func main() {
	data, err := io.ReadAll(os.Stdin)
	if err != nil {
		fmt.Println("could not read input:", err)
		return
	}
	gateA, gateB, _ := strings.Cut(strings.ReplaceAll(string(data), "\r\n", "\n"), "\n\n")
	a, b := numbers(gateA), numbers(gateB)
	fmt.Println("all scans in order:", merge(a, b))
	fmt.Println("tickets scanned at both gates:", both(a, b))
}
Go runtime not loaded yet

15 lines · 71 B of the 1 MB limit. Submit always uses the lesson's own input.