algospatterns
two pointers
two indexes walk the array, from both ends or at two speeds, so a pair search takes one pass.
two indexes walk one array in a single pass. from both ends, each sum rules out one end for good. at two speeds, fast reads every item and slow marks where the next kept one goes.
- time
- O(n) at most n - 1 sums, against n(n - 1) / 2 for every pair
- space
- O(1) two indexes, nothing else
- in place
- yes dedupe writes over the array it reads
- needs
- sorted input the pair walk leans on the order. sorting first is O(n log n)
- a pair with a given sum, in a sorted array
- removing repeats, or filtering, in place
- is it a palindrome
- merging two sorted lists
- partition, in quicksort
- a cycle in a linked list
on this page
two pointers is a shape for a loop, not one algorithm. two indexes walk one array, and the walk is built so that every step settles something for good. the question that shows it best: in a sorted array, is there a pair that adds up to a target? checking every pair is a loop inside a loop. with one index at each end, every sum throws out one end, and the whole search is one pass.
the idea
an animation in six steps. eight sorted numbers, 3, 5, 8, 10, 11, 12, 16 and 19, as bars, with a line above them for each sum and the target, 20, in the footer. lo, in cyan, starts under the 3 and hi, in amber, under the 19. 3 + 19 = 22 is more than 20: the 19 dims and hi moves in to the 16. 3 + 16 = 19 is less than 20: the 3 dims and lo moves in to the 5. then two quicker moves: 5 + 16 = 21 sends hi in to the 12, and 5 + 12 = 17 sends lo in to the 8. 8 + 12 = 20: both bars turn white, found at indexes 2 and 5. the footer counts the sums, 5 in the end, and the pairs left, from 28 down to 6.
watch it run
step through a real run on random numbers. lo is cyan, hi is amber, and the bars they’ve ruled out dim. the pseudocode follows along. switch to dedupe for the other shape: slow is cyan, fast is amber, and a value turns white as it’s written.
new numbers pick a target that's there.
lo at 0, hi at 7: the two ends. 28 pairs to rule out, and the target is 20
- target
- 20
- sums
- 0
- step
- 1 of 11
pair_with_sum(a, target): # a sorted, smallest first lo, hi = 0, len(a) - 1 # the two ends while lo < hi: s = a[lo] + a[hi] if s == target: return lo, hi if s < target: lo += 1 # a[lo] is too small for anything left else: hi -= 1 # a[hi] is too big for anything left return none # they met: every pair is ruled out dedupe(a): # a sorted. keeps the first of each run, in place if len(a) == 0: return 0 slow = 0 # the last kept item for fast in range(1, len(a)): if a[fast] != a[slow]: slow += 1 a[slow] = a[fast] # the next kept item goes right after return slow + 1 # the kept items are a[0:slow + 1]an interactive stepper with two modes. pair with sum: bars for 8, 12 or 16 sorted numbers and a target, with lo in cyan under the left end and hi in amber under the right. each step shows the sum, then one pointer moves in and the bar it leaves dims, until the pair is found, in white, or the pointers meet. new numbers picks a target that's there, and a button asks for one that isn't. dedupe: a sorted array with repeats, slow in cyan under the last kept item and fast in amber under the item it reads. a new value turns white as it's written to the slot after slow, read repeats dim, and at the end the leftover past the kept items dims. the matching pseudocode line is highlighted, with counters for the target and the sums, or the compares and moves, and the step.
try it
the whole walk hangs on one call: which pointer moves. make it.
the target is 20. lo is on 5 and hi on 16. what happens next?
pick one.
a practice exercise on small sorted arrays, drawn as a row of cells with their indexes. some questions show lo and hi mid-walk, with the cells they've ruled out dimmed, and ask whether lo moves in, hi moves in, or the pair is found. others ask which indexes the walk returns, where another pair that fits is the trap, how many sums it checks before it stops, or how many items dedupe keeps.
pseudocode
pair_with_sum(a, target): # a sorted, smallest first
lo, hi = 0, len(a) - 1 # the two ends
while lo < hi:
s = a[lo] + a[hi]
if s == target: return lo, hi
if s < target: lo += 1 # a[lo] is too small for anything left
else: hi -= 1 # a[hi] is too big for anything left
return none # they met: every pair is ruled out
dedupe(a): # a sorted. keeps the first of each run, in place
if len(a) == 0: return 0
slow = 0 # the last kept item
for fast in range(1, len(a)):
if a[fast] != a[slow]:
slow += 1
a[slow] = a[fast] # the next kept item goes right after
return slow + 1 # the kept items are a[0:slow + 1]lo < hi is the whole loop condition: a pair is two different indexes, so the walk stops when they meet. dedupe keeps slow on the last kept item, not on the next free slot, so the compare reads a[slow] and the write goes to slow + 1.
the move, up close
rows: lo, in cyan. columns: hi, in amber. each cell is a pair's sum
lo at 0, hi at 7: the two ends. 28 pairs to rule out, and the target is 20
- pairs left
- 28 of 28
- sums
- 0
a grid of the 28 pairs the page's eight numbers make, lo down the rows and hi across the columns, each cell holding the pair's sum. a slider steps through the walk. at the start all 28 are in play. the first sum, 3 + 19, strikes out column 7, the seven pairs with 19, in amber. the second, 3 + 16, strikes out row 0, the six pairs left with 3, in cyan. then column 6, five pairs, and row 1, four. after four moves, 22 of the 28 are struck out and 6 are left, and the fifth sum lands on 8 + 12 = 20, which turns white.
- a sum rules out an end, not a pair. when
a[lo] + a[hi]is too small, every partnera[lo]could still have is at mosta[hi]: everything bigger is gone already. soa[lo]is too small with all of them, and lo moves. too big is the mirror:a[hi]is too big with everything left, sincea[lo]is the smallest left - nothing is skipped. a pair only leaves the grid when one of its ends is ruled out, and an end is only ruled out when no partner can work. so if a pair adds up to the target, the walk stays inside it until it lands on it
- the count. each sum strikes out a whole row or column of what’s left, and moves a pointer in by one. the pointers start n - 1 apart, so after n - 1 sums they meet and the grid is empty. on the page’s 8 numbers, four moves strike out 7, 6, 5 and 4 pairs, and the fifth sum is the answer
- which pair, when several fit. lo never passes a value that still has a partner, so the walk returns the pair with the smallest lo, and the biggest hi for it. for 1, 2, 3, 4, 5 and a target of 6, that’s 1 + 5 at 0 and 4, not 2 + 4
- dedupe’s invariant. everything up to slow is the kept list, every item fast has read is in it or a repeat of its last entry, and slow never passes fast, so a write never lands on an item that hasn’t been read
complexity
| the walk | every pair | |
|---|---|---|
| sums, worst | n - 1 | n(n - 1) / 2 |
| extra space | O(1) | O(1) |
| needs | sorted input | nothing |
dedupe reads every item once, n - 1 compares, and writes each kept item at most once: O(n) time, O(1) space. the walk is O(n) too, but it leans on the order, and sorting first is O(n log n). when the input arrives sorted, the pass is all it costs.
- walk, at most
- 1,023 sums
- walk, on average
- 638 sums
- every pair
- 523,776 sums
a line chart of sums against how many numbers there are, from 8 to 1,024 on a doubling scale, with the top at 1,500. checking every pair, dashed amber, climbs off the top between 32 and 64 numbers: 496 pairs at 32, 2,016 at 64 and 523,776 at 1,024. the walk's worst case, n - 1, in cyan, doubles each time the numbers do: 7 at 8 and 1,023 at 1,024. under it, dashed cyan, the walk's average over seeded runs whose target is the sum of a random pair: 4.6 at 8 and 638 at 1,024. a slider picks a size and reads off all three.
on 1,024 numbers the walk checks at most 1,023 sums, where every pair is 523,776. when the target is there it usually stops early: over seeded runs whose target was the sum of a random pair, it averaged 638 sums on 1,024 numbers, a little under two thirds of the worst case. lo walks in to the pair’s left end and hi to its right end, and for a random pair each end is about a third of the way in.
implementations
each tab is the real file from the repo, checked by its tests (go test, cargo test, vitest, make test, swift test, python -m unittest), including 2000 seeded sorted arrays against checking every pair, and 2000 more against a set for dedupe. every tab returns the same pair when several fit, the one with the smallest lo and the biggest hi for it, and leaves the same leftover past the kept items, so the tests can check the arrays themselves: 1, 1, 2, 3, 3, 3, 5, 5 keeps 4 and ends as 1, 2, 3, 5, 3, 3, 5, 5. no pair is where they differ: go returns false as a third value, rust None, typescript null, c returns false and leaves its two out-params alone, swift nil, and python None.
// Package twopointers is a reference for two pointers: two indexes walk one array, so a search that would
// look at every pair takes one pass. from both ends: lo and hi start at the ends of a sorted array and
// close in, and each sum rules out one end for good. at two speeds: fast reads every item and slow marks
// where the next kept one goes, so a filter runs in place.
package twopointers
// PairWithSum returns two indexes lo < hi with a[lo] + a[hi] == target and true, or 0, 0, false when no
// pair adds up to it. a must be sorted, smallest first. When more than one pair fits, the walk reaches the
// one with the smallest lo first, and the biggest hi for that lo. At most len(a) - 1 sums: every sum moves
// one pointer in by one, and the walk stops when they meet.
func PairWithSum(a []int, target int) (lo, hi int, ok bool) {
lo, hi = 0, len(a)-1
for lo < hi {
sum := a[lo] + a[hi]
if sum == target {
return lo, hi, true
}
// a[hi] is the biggest item left, so a sum that's too small rules a[lo] out with everything left.
// a sum that's too big rules a[hi] out the same way, since a[lo] is the smallest left
if sum < target {
lo++
} else {
hi--
}
}
return 0, 0, false
}
// Dedupe keeps the first item of each run of equal items, in place, and returns how many are kept: a[:k]
// holds them in order, and what's past k is leftover, not cleared. On a sorted slice that's every value
// once. fast reads every item, and slow sits on the last kept one.
func Dedupe(a []int) int {
if len(a) == 0 {
return 0
}
slow := 0
for fast := 1; fast < len(a); fast++ {
if a[fast] != a[slow] {
slow++
a[slow] = a[fast] // the next kept item goes right after the last one
}
}
return slow + 1
}//! two pointers: two indexes walk one array, so a search that would look at every pair takes one pass. from both ends: lo and hi start at the ends of a sorted array and close in, and each sum rules out one end for good. at two speeds: fast reads every item and slow marks where the next kept one goes, so a filter runs in place.
/// Two indexes `lo < hi` with `a[lo] + a[hi] == target`, or `None` when no pair adds up to it.
/// `a` must be sorted, smallest first, and each sum must fit in an `i32`. When more than one pair
/// fits, the walk reaches the one with the smallest `lo` first, and the biggest `hi` for that
/// `lo`. At most n - 1 sums on n items: every sum moves one pointer in by one, and the walk stops
/// when they meet.
pub fn pair_with_sum(a: &[i32], target: i32) -> Option<(usize, usize)> {
let mut lo = 0;
let mut hi = a.len().saturating_sub(1); // len() - 1 would underflow on an empty slice
while lo < hi {
let sum = a[lo] + a[hi];
if sum == target {
return Some((lo, hi));
}
// a[hi] is the biggest item left, so a sum that's too small rules a[lo] out with
// everything left. a sum that's too big rules a[hi] out the same way, since a[lo] is the
// smallest left
if sum < target {
lo += 1;
} else {
hi -= 1;
}
}
None
}
/// Keeps the first item of each run of equal items, in place, and returns how many are kept:
/// `a[..k]` holds them in order, and what's past `k` is leftover, not cleared. On a sorted slice
/// that's every value once. `fast` reads every item, and `slow` sits on the last kept one.
pub fn dedupe(a: &mut [i32]) -> usize {
if a.is_empty() {
return 0;
}
let mut slow = 0;
for fast in 1..a.len() {
if a[fast] != a[slow] {
slow += 1;
a[slow] = a[fast]; // the next kept item goes right after the last one
}
}
slow + 1
}
#[cfg(test)]
mod tests {
use super::*;
use std::collections::BTreeSet;
/// xorshift32 seeded with `seed`, like the other tests here: each call gives the next number.
fn xorshift32(seed: u32) -> impl FnMut() -> usize {
let mut state = seed;
move || {
state ^= state << 13;
state ^= state >> 17;
state ^= state << 5;
state as usize
}
}
/// Every pair the walk could return, checked one by one: the smallest lo, and the biggest hi
/// for it.
fn brute_force(a: &[i32], target: i32) -> Option<(usize, usize)> {
for i in 0..a.len() {
for j in (i + 1..a.len()).rev() {
if a[i] + a[j] == target {
return Some((i, j));
}
}
}
None
}
// the page's two examples
const PAGE: [i32; 8] = [3, 5, 8, 10, 11, 12, 16, 19];
const RUNS: [i32; 8] = [1, 1, 2, 3, 3, 3, 5, 5];
// pair with sum
#[test]
fn an_empty_array_has_no_pair_and_neither_does_one_item_a_pair_is_two_different_indexes() {
assert_eq!(
(pair_with_sum(&[], 5), pair_with_sum(&[5], 10)),
(None, None)
);
}
#[test]
fn the_pages_8_numbers_20_is_8_plus_12_at_2_and_5() {
assert_eq!(pair_with_sum(&PAGE, 20), Some((2, 5)));
assert_eq!(pair_with_sum(&PAGE, 17), Some((1, 5)));
// the ends: the smallest pair and the biggest
assert_eq!(
(pair_with_sum(&PAGE, 8), pair_with_sum(&PAGE, 35)),
(Some((0, 1)), Some((6, 7)))
);
}
#[test]
fn no_pair_too_small_too_big_or_in_between_the_sums_there_are() {
assert_eq!(
(
pair_with_sum(&PAGE, 7),
pair_with_sum(&PAGE, 36),
pair_with_sum(&PAGE, 25)
),
(None, None, None)
);
}
#[test]
fn several_pairs_the_one_with_the_smallest_lo_and_the_biggest_hi_for_it() {
// 1 + 5 and 2 + 4 both make 6: the walk reaches 0 and 4 first
assert_eq!(pair_with_sum(&[1, 2, 3, 4, 5], 6), Some((0, 4)));
// two copies of 5 pair with 1: the far one
assert_eq!(pair_with_sum(&[1, 5, 5], 6), Some((0, 2)));
assert_eq!(pair_with_sum(&[2, 2, 2], 4), Some((0, 2)));
}
#[test]
fn negatives_and_zero() {
assert_eq!(pair_with_sum(&[-4, -1, 0, 3, 5], -1), Some((0, 3)));
// 0 + 0 would need the same index twice
assert_eq!(pair_with_sum(&[-4, -1, 0, 3, 5], 0), None);
assert_eq!(pair_with_sum(&[-3, 0, 3], 0), Some((0, 2)));
}
#[test]
fn agrees_with_checking_every_pair_on_2000_seeded_sorted_arrays() {
let mut next = xorshift32(42);
// small values, so most arrays have duplicates and most targets have several pairs or none
for _ in 0..2000 {
let mut a: Vec<i32> = (0..next() % 31).map(|_| (next() % 20) as i32).collect();
a.sort();
let target = (next() % 42) as i32 - 2;
assert_eq!(pair_with_sum(&a, target), brute_force(&a, target));
}
}
// dedupe
#[test]
fn an_empty_array_keeps_nothing_and_one_item_keeps_itself() {
let mut one = [5];
assert_eq!((dedupe(&mut []), dedupe(&mut one), one), (0, 1, [5]));
}
#[test]
fn the_pages_8_items_keep_4_1_2_3_5_past_them_the_array_is_whatever_was_there() {
let mut a = RUNS;
assert_eq!(dedupe(&mut a), 4);
assert_eq!(a[..4], [1, 2, 3, 5]);
assert_eq!(a, [1, 2, 3, 5, 3, 3, 5, 5]);
}
#[test]
fn all_the_same_keeps_one_and_all_different_keeps_everything_where_it_was() {
let mut same = [7, 7, 7, 7];
let mut distinct = [1, 2, 3];
assert_eq!(
(dedupe(&mut same), same[0], dedupe(&mut distinct), distinct),
(1, 7, 3, [1, 2, 3])
);
}
#[test]
fn a_run_at_each_end() {
let mut a = [0, 0, 0, 1, 2, 9, 9];
assert_eq!(dedupe(&mut a), 4);
assert_eq!(a[..4], [0, 1, 2, 9]);
}
#[test]
fn unsorted_input_it_only_collapses_runs_so_a_value_that_comes_back_stays() {
let mut a = [2, 1, 1, 2];
assert_eq!(dedupe(&mut a), 3);
assert_eq!(a[..3], [2, 1, 2]);
}
#[test]
fn agrees_with_a_set_on_2000_seeded_sorted_arrays() {
let mut next = xorshift32(7);
for _ in 0..2000 {
let mut a: Vec<i32> = (0..next() % 31).map(|_| (next() % 10) as i32).collect();
a.sort();
// each value once, smallest first: on a sorted slice that's the order they come in
let set: BTreeSet<i32> = a.iter().copied().collect();
let want: Vec<i32> = set.into_iter().collect();
let kept = dedupe(&mut a);
assert_eq!(kept, want.len());
assert_eq!(a[..kept], want);
}
}
}/**
* Two pointers: two indexes walk one array, so a search that would look at every pair takes one pass. From both
* ends: lo and hi start at the ends of a sorted array and close in, and each sum rules out one end for good. At
* two speeds: fast reads every item and slow marks where the next kept one goes, so a filter runs in place.
*/
/**
* Two indexes lo < hi with a[lo] + a[hi] == target, or null when no pair adds up to it. a must be sorted, smallest
* first. When more than one pair fits, the walk reaches the one with the smallest lo first, and the biggest hi
* for that lo. At most a.length - 1 sums: every sum moves one pointer in by one, and the walk stops when they meet.
*/
export function pairWithSum(a: readonly number[], target: number): [number, number] | null {
let lo = 0;
let hi = a.length - 1;
while (lo < hi) {
const sum = a[lo] + a[hi];
if (sum === target) return [lo, hi];
// a[hi] is the biggest item left, so a sum that's too small rules a[lo] out with everything left. a sum
// that's too big rules a[hi] out the same way, since a[lo] is the smallest left
if (sum < target) lo++;
else hi--;
}
return null;
}
/**
* Keeps the first item of each run of equal items, in place, and returns how many are kept: a[0:k] holds them in
* order, and what's past k is leftover, not cleared. On a sorted array that's every value once. fast reads every
* item, and slow sits on the last kept one.
*/
export function dedupe(a: number[]): number {
if (a.length === 0) return 0;
let slow = 0;
for (let fast = 1; fast < a.length; fast++) {
if (a[fast] !== a[slow]) {
slow++;
a[slow] = a[fast]; // the next kept item goes right after the last one
}
}
return slow + 1;
}/* two pointers: two indexes walk one array, so a search that would look at every pair takes one pass. from both ends: lo and hi start at the ends of a sorted array and close in, and each sum rules out one end for good. at two speeds: fast reads every item and slow marks where the next kept one goes, so a filter runs in place. */
#include "two_pointers.h"
/* n = 0 stops first: hi = n - 1 would wrap around to SIZE_MAX. every sum moves one pointer in by
one, and the walk stops when they meet, so it takes at most n - 1 sums */
bool pair_with_sum(const int *a, size_t n, int target, size_t *lo_out, size_t *hi_out) {
if (n == 0) return false;
size_t lo = 0, hi = n - 1;
while (lo < hi) {
int sum = a[lo] + a[hi];
if (sum == target) {
*lo_out = lo;
*hi_out = hi;
return true;
}
/* a[hi] is the biggest item left, so a sum that's too small rules a[lo] out with
everything left. a sum that's too big rules a[hi] out the same way, since a[lo] is the
smallest left */
if (sum < target) lo++;
else hi--;
}
return false;
}
/* the first item is always kept, so slow starts on it. fast reads every item after it, and slow
sits on the last kept one */
size_t dedupe(int *a, size_t n) {
if (n == 0) return 0; /* no first item */
size_t slow = 0;
for (size_t fast = 1; fast < n; fast++) {
if (a[fast] != a[slow]) {
slow++;
a[slow] = a[fast]; /* the next kept item goes right after the last one */
}
}
return slow + 1;
}/// two pointers: two indexes walk one array, so a search that would look at every pair takes one pass. from both ends: lo and hi start at the ends of a sorted array and close in, and each sum rules out one end for good. at two speeds: fast reads every item and slow marks where the next kept one goes, so a filter runs in place.
/// two indexes lo < hi with a[lo] + a[hi] == target, or nil when no pair adds up to it. a must be sorted, smallest
/// first. when more than one pair fits, the walk reaches the one with the smallest lo first, and the biggest hi
/// for that lo. at most a.count - 1 sums: every sum moves one pointer in by one, and the walk stops when they meet.
/// each sum has to fit in an Int, or swift traps
public func pairWithSum(_ a: [Int], _ target: Int) -> (Int, Int)? {
var lo = 0
var hi = a.count - 1
while lo < hi {
let sum = a[lo] + a[hi]
if sum == target { return (lo, hi) }
// a[hi] is the biggest item left, so a sum that's too small rules a[lo] out with everything left. a sum
// that's too big rules a[hi] out the same way, since a[lo] is the smallest left
if sum < target { lo += 1 } else { hi -= 1 }
}
return nil
}
/// keeps the first item of each run of equal items, in place, and returns how many are kept: a[0..<k] holds them
/// in order, and what's past k is leftover, not cleared. on a sorted array that's every value once. fast reads
/// every item, and slow sits on the last kept one
public func dedupe(_ a: inout [Int]) -> Int {
if a.isEmpty { return 0 }
var slow = 0
for fast in a.indices.dropFirst() {
if a[fast] != a[slow] {
slow += 1
a[slow] = a[fast] // the next kept item goes right after the last one
}
}
return slow + 1
}"""two pointers: two indexes walk one array, so a search that would look at every pair takes one pass. from both ends: lo and hi start at the ends of a sorted array and close in, and each sum rules out one end for good. at two speeds: fast reads every item and slow marks where the next kept one goes, so a filter runs in place."""
from __future__ import annotations
def pair_with_sum(a: list[int], target: int) -> tuple[int, int] | None:
"""Return two indexes lo < hi with a[lo] + a[hi] == target, or None when no pair adds up to it.
a must be sorted, smallest first. When more than one pair fits, the walk reaches the one with the
smallest lo first, and the biggest hi for that lo. At most len(a) - 1 sums: every sum moves one pointer
in by one, and the walk stops when they meet.
"""
lo, hi = 0, len(a) - 1
while lo < hi:
s = a[lo] + a[hi]
if s == target:
return lo, hi
# a[hi] is the biggest item left, so a sum that's too small rules a[lo] out with everything left.
# a sum that's too big rules a[hi] out the same way, since a[lo] is the smallest left
if s < target:
lo += 1
else:
hi -= 1
return None
def dedupe(a: list[int]) -> int:
"""Keep the first item of each run of equal items, in place, and return how many are kept.
a[:k] holds them in order, and what's past k is leftover, not cleared. On a sorted list that's every
value once. fast reads every item, and slow sits on the last kept one.
"""
if not a:
return 0
slow = 0
for fast in range(1, len(a)):
if a[fast] != a[slow]:
slow += 1
a[slow] = a[fast] # the next kept item goes right after the last one
return slow + 1pitfalls
- unsorted input. the argument needs the order. on an unsorted array the walk still returns something, and it’s wrong. sort first, or use a hash table and give up the O(1) space
lo <= hi. with<=the last step checksa[lo] + a[lo], one item used twice. a pair is two different indexes, so the loop runs whilelo < hi- moving the wrong end. too small means lo moves, too big means hi moves. swap them and the walk skips the answer and still ends after n - 1 steps, with nothing to say it went wrong
- moving both on a match. some versions move both pointers in after a match to look for the next pair. with repeats that skips pairs: after 2 + 8, the next 2 may pair with the same 8. skip past the repeats on each side instead
- slow on the next free slot. off by one both ways: the compare reads the wrong item, or the count comes out one short. keep slow on the last kept item and return
slow + 1 - reading the tail. after dedupe, the items past the count are leftover, and they look like real data. go’s
slices.Compactclears them for the garbage collector; most code just has to remember not to read them1
variants
- two speeds. move fast two nodes for every one slow takes, and in a linked list with a cycle they meet inside it: floyd’s cycle check. the name comes from knuth, who credited floyd in 1969, though it doesn’t appear in floyd’s own papers2. the same two pointers, n apart, find the nth node from the end in one pass. the linked list page has both
- two arrays. one pointer per sorted list, always taking the smaller front item: the merge on the merge sort page. the same loop from the back merges a second array into spare room at the end of the first
- partition. lo walks right past the small items, hi walks left past the big ones, and they swap what they stop on: hoare’s partition, in quicksort. dutch national flag is the three-way version, with a third pointer for the items equal to the pivot
- 3sum. sort, then for each item run the walk on the rest, for the item’s negative: O(n²) instead of O(n³). skipping repeats on all three keeps the triples unique
- both ends, other questions. is it a palindrome: lo and hi compare and move in together. container with most water: move the shorter side, by the same argument as the sum. squares of a sorted array: the biggest square is at one end or the other, so fill the answer from the back
- a window instead of a pair. when lo and hi both move right, the range between them is a window, and what you keep about it is the point: that’s sliding window
practice
- two sum ii (opens in a new tab): the pair walk, with 1-based indexes
- remove duplicates from sorted array (opens in a new tab): dedupe, as on this page
- valid palindrome (opens in a new tab): both ends moving in, skipping what isn’t a letter
- squares of a sorted array (opens in a new tab): both ends, filling the answer from the back
- container with most water (opens in a new tab): move the shorter side
- 3sum (opens in a new tab): sort, then the walk for every item
how real libraries do it
- rust.
Vec::dedupremoves consecutive repeats, every duplicate when the vector is sorted. it’sdedup_by, which keeps areadoffset for the item to check and awriteoffset for where the next kept one goes, after a first scan that returns early when nothing repeats3 - go.
slices.Compactreplaces each run of equal items with one copy, like unix’suniq, in place, and zeroes the slots between the new length and the old one1 - c++.
std::uniqueis the same walk. libc++ finds the first two equal neighbors, then one iterator marks the last kept item while another reads ahead, and returns the new end. what’s past it is leftover4 - python. no dedupe in place. a set, or
dict.fromkeysto keep the order, makes a new list
sources
-
slices.go (opens in a new tab) at go1.27.3:
Compactreplaces consecutive runs of equal elements with a single copy, like the unixuniqcommand, modifies the slice in place, returns it with a smaller length, and zeroes the elements between the new length and the original one. ↩ ↩2 -
cycle detection (opens in a new tab) on wikipedia: floyd’s algorithm moves two pointers through the sequence at different speeds. it’s named after robert w. floyd because donald knuth credited him with it in 1969, in the art of computer programming, vol. 2, but it doesn’t appear in floyd’s published work, and knuth’s statement is its first known appearance in print. ↩
-
vec/mod.rs (opens in a new tab) at rust 1.99.1:
dedupremoves consecutive repeated elements, every duplicate if the vector is sorted, by callingdedup_by.dedup_by(opens in a new tab) keeps areadoffset, the element to check, and awriteoffset, the place for the next non-duplicate, and its loop (opens in a new tab) compares the item atreadwith the one beforewrite, drops a duplicate in place, and copies anything else fromreadtowrite. ↩ -
unique.h (opens in a new tab) in libc++ at llvmorg-23.1.4:
__uniquefinds the first equal neighbors withadjacent_find, then moves each item that differs from the last kept one into the slot after it, and returns the position past the last kept item. ↩