Two Pointers
Two pointers is an array technique that moves a pair of indices toward a goal. In TypeScript the interesting part is typing the array, the indices, and the pair you return, so an out-of-bounds read is visible.
Detailed Explanation
The algorithm is a JavaScript loop: left starts at 0, right at length - 1, and you move one or both until they meet. TypeScript does not add a two-pointer primitive. What it adds is a type for the collection and a type for the result.
Use readonly T[] if the loop only reads. Use T[] if you swap in place. Swapping is the usual in-place sort/partition form; the signature should say that (items: T[]) so callers do not pass a readonly array and then get a copy they did not want — or a type error they did.
Indices are number. The type system does not track that left <= right or that both are in range. items[left] is T by default, even when items is empty and right is -1. That is the same hole as every index read. noUncheckedIndexedAccess makes items[left] a T | undefined, which is honest and noisy inside a tight loop. The usual pattern with that flag on is a local guard or a for that iterates values instead of indexes when you can.
The result of a two-pointer search is often a pair: the two indices, or the two values. Type that as a tuple [number, number] or [T, T], or as { left: T; right: T }. A tuple matches how you think about positions. An object matches how you will return it from a public API.
When the two pointers walk two different arrays (merge, intersection), the function is generic in two parameters: <A, B>(left: readonly A[], right: readonly B[]). When they walk one array for a pair that sums to a target, one T plus a constraint (T extends number) is enough.
Do not encode the algorithm in the type system. A type that "proves" left is in range is a research project. Annotate the inputs, annotate the pair you return, and write the loop in JavaScript. See the JavaScript two-pointers page for the technique itself.
Code Examples
1. In-place reverse — mutable array in the signature.
// 1. In-place reverse — mutable array in the signature.
function reverse<T>(items: T[]): void {
let left = 0;
let right = items.length - 1;
while (left < right) {
const tmp = items[left];
items[left] = items[right];
items[right] = tmp;
left += 1;
right -= 1;
}
}
const letters = ["a", "b", "c"];
reverse(letters);
console.log(letters); // ["c", "b", "a"]2. Two-sum on a sorted list — readonly input, tuple result.
// 2. Two-sum on a sorted list — readonly input, tuple result.
function twoSumSorted(
nums: readonly number[],
target: number,
): [number, number] | undefined {
let left = 0;
let right = nums.length - 1;
while (left < right) {
const sum = nums[left] + nums[right];
if (sum === target) return [left, right];
if (sum < target) left += 1;
else right -= 1;
}
return undefined;
}
console.log(twoSumSorted([1, 2, 4, 7], 6)); // [1, 2]3. Merging two typed arrays.
// 3. Merging two typed arrays.
function mergeSorted(a: readonly number[], b: readonly number[]): number[] {
const out: number[] = [];
let i = 0;
let j = 0;
while (i < a.length && j < b.length) {
if (a[i] <= b[j]) out.push(a[i++]);
else out.push(b[j++]);
}
while (i < a.length) out.push(a[i++]);
while (j < b.length) out.push(b[j++]);
return out;
}Common Gotchas
Empty arrays make `right === -1`
`items[right]` is still typed as `T` without `noUncheckedIndexedAccess`. Handle `length < 2` first.
A `readonly T[]` parameter forbids in-place swaps
choose mutability in the signature on purpose.
The returned pair should be a tuple or a named object, not `number[]`
`number[]` forgets that there are exactly two positions.
Two different element types need two generics
do not union them into `T` unless the algorithm really mixes them.