algospatterns

two pointers

two indexes walk the array, from both ends or at two speeds, so a pair search takes one pass.

report a mistake
.md

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)
reach for it
  • 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
  1. the idea
  2. watch it run
  3. try it
  4. pseudocode
  5. the move, up close
  6. complexity
  7. implementations
  8. pitfalls
  9. variants
  10. practice
  11. how real libraries do it
  12. sources

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

eight numbers, sorted, and a target: 20. lo starts at the left end, on 3, and hi at the right end, on 19. is there a pair that adds up to 20?

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
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]

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.

0 / 0 right

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

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

123456701234568111314151922131516172124181920242721222629232730283135

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.

complexity

the walkevery pair
sums, worstn - 1n(n - 1) / 2
extra spaceO(1)O(1)
needssorted inputnothing

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.

05001k1.5k81281024every pair
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.

go/algos/twopointers/twopointers.go
// 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
}
rust/algos/src/two_pointers.rs
//! 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);
        }
    }
}
site/src/visuals/two-pointers/two-pointers.ts
/**
 * 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;
}
c/algos/two_pointers.c
/* 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;
}
swift/algos/TwoPointers.swift
/// 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
}
python/algos/two_pointers.py
"""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 + 1

pitfalls

variants

practice

how real libraries do it

sources

  1. slices.go (opens in a new tab) at go1.27.3: Compact replaces consecutive runs of equal elements with a single copy, like the unix uniq command, modifies the slice in place, returns it with a smaller length, and zeroes the elements between the new length and the original one. ↩ ↩2

  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. ↩

  3. vec/mod.rs (opens in a new tab) at rust 1.99.1: dedup removes consecutive repeated elements, every duplicate if the vector is sorted, by calling dedup_by. dedup_by (opens in a new tab) keeps a read offset, the element to check, and a write offset, the place for the next non-duplicate, and its loop (opens in a new tab) compares the item at read with the one before write, drops a duplicate in place, and copies anything else from read to write. ↩

  4. unique.h (opens in a new tab) in libc++ at llvmorg-23.1.4: __unique finds the first equal neighbors with adjacent_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. ↩