Two pointers
Two pointers is a technique that walks a slice with a pair of indexes that only move forward (or from both ends). Each element is visited a constant number of times, so the extra work is O(n) after any required sort.
Detailed Explanation
You need two indexes that together describe a candidate: the start and end of a subarray, or the smallest and largest remaining numbers. Instead of a nested i/j loop (O(n²)), you move one index when a condition fails and the other when it holds. Because they never rewind, the total moves are O(n).
Opposite ends. Sorted pair-sum: lo, hi := 0, len(s)-1. If s[lo]+s[hi] is too small, lo++. If too large, hi--. This requires a sorted slice. Sort first if the problem allows reordering, or copy and sort if it does not.
Same direction. Slow and fast on a linked structure, or read and write indexes to compact a slice in place: if keep { s[w] = s[r]; w++ }. The write pointer lags. This is how you remove zeros or unique a sorted slice without a second allocation.
Invariants matter more than the name. Write down what lo and hi mean at the top of the loop ("everything before lo is processed"). Off-by-one errors come from moving both pointers, or from using <= when the pointers have already crossed.
Go details. Indexes are int. An empty slice should return before you compute s[hi]. Prefer for lo < hi or for i, j := 0, 0; i < len(s); i++ with a clear second index. Slices of bytes ([]byte) use the same pattern for in-place string-like edits.
What it costs. O(n) time after an optional O(n log n) sort, O(1) extra space when you mutate in place. A map-based pair-sum is O(n) time without sorting and O(n) space. Pick the variant that matches whether you may reorder and whether you need the original indexes.
Code Examples
package main
import (
"fmt"
"slices"
)
func hasPairSum(s []int, target int) bool {
slices.Sort(s)
lo, hi := 0, len(s)-1
for lo < hi {
sum := s[lo] + s[hi]
switch {
case sum < target:
lo++
case sum > target:
hi--
default:
return true
}
}
return false
}
func compactNonzero(s []int) []int {
w := 0
for _, v := range s {
if v != 0 {
s[w] = v
w++
}
}
return s[:w]
}
func main() {
fmt.Println(hasPairSum([]int{3, 1, 4}, 5))
fmt.Println(compactNonzero([]int{0, 2, 0, 3}))
}Common Gotchas
Reading `s[hi]` when `len(s) == 0` panics
handle empty and single-element slices first.
Opposite-end pair-sum is wrong on unsorted data
sort a copy if order matters to the caller.
Moving both pointers in one iteration can skip a valid pair
move the one the condition names.
In-place compact aliases the same array
leftover tail still exists in capacity until you clip.