typescript / intermediate
Snippet
In-Place Array Deduplication with Two-Pointer Technique
The two-pointer technique allows modifying array elements in-place without allocating temporary secondary arrays or Set instances. Mutating the array length directly truncates trailing duplicates in O(n) time.
snippet.ts
typescript
1
2
3
4
5
6
7
8
9
10
11
12
function deduplicateSortedArray<T extends string | number>(items: T[]): T[] {if (items.length <= 1) return items;let writeIndex = 1;for (let readIndex = 1; readIndex < items.length; readIndex++) {if (items[readIndex] !== items[writeIndex - 1]) {items[writeIndex] = items[readIndex];writeIndex++;}}items.length = writeIndex;return items;}
Breakdown
1
function deduplicateSortedArray<T extends string | number>(items: T[]): T[] {
Defines a generic function accepting a sorted array of primitive values to be modified in-place.
2
let writeIndex = 1;
Initializes the write pointer to track the position of unique elements.
3
if (items[readIndex] !== items[writeIndex - 1]) {
Compares the current read element with the last written unique element.
4
items.length = writeIndex;
Truncates the array in-place to remove leftover duplicate entries without allocation.