THN Interview Prep

26. Remove Duplicates from Sorted Array

At a Glance

  • Topic: arrays-hashing
  • Pattern: Two Pointers
  • Difficulty: Easy
  • Companies: Amazon, Google, Meta, Microsoft, Bloomberg
  • Frequency: High
  • LeetCode: 26

Problem (one-liner)

Given sorted integers numbers, remove duplicates in-place so each unique value appears once. Return uniqueCount; first uniqueCount slots contain sorted unique values in order.

Recognition Cues

  • "Sorted array", "remove duplicates in-place"
  • Slow pointer for write position, fast for scan

Diagram

At-a-glance flow (replace with problem-specific Mermaid as you refine this note). camelCase node IDs; no spaces in IDs.

Loading diagram…

Approaches

  • Brute force — new array or hash set — O(n) space extra.
  • Better — same two-pointer but confusing variable names.
  • OptimalwriteIndex starts at 1; copy forward when numbers[scan] != numbers[writeIndex-1]O(n) time / O(1) extra space.

Optimal Solution

Go

package main

func removeDuplicates(numbers []int) int {
	if len(numbers) == 0 {
		return 0
	}
	writeIndex := 1
	for scanIndex := 1; scanIndex < len(numbers); scanIndex++ {
		if numbers[scanIndex] != numbers[writeIndex-1] {
			numbers[writeIndex] = numbers[scanIndex]
			writeIndex++
		}
	}
	return writeIndex
}

JavaScript

function removeDuplicates(numbers) {
	if (numbers.length === 0) {
		return 0;
	}
	let writeIndex = 1;
	for (let scanIndex = 1; scanIndex < numbers.length; scanIndex++) {
		if (numbers[scanIndex] !== numbers[writeIndex - 1]) {
			numbers[writeIndex] = numbers[scanIndex];
			writeIndex++;
		}
	}
	return writeIndex;
}

Walkthrough

Input: numbers = [0,0,1,1,1,2,2,3,3,4]

scanIndexwriteIndexcompare with prev uniqueaction
110 vs 0skip duplicate
211 vs 0write 1 at 1, wi++
321 vs 1skip
421 vs 1skip
522 vs 1write 2, wi++

Final prefix [0,1,2,3,4,...] length 5.

Edge Cases

  • Empty array → 0.
  • All distinct → return len(numbers).
  • Single element → 1.

Pitfalls

  • Returning new slice instead of mutating in-place when required.
  • Comparing with wrong prior element after compaction.

Similar Problems

Variants

  • Allow at most k duplicates (LeetCode 80).
  • Linked list dedupe.

Mind-Map Tags

#two-pointers #sorted #dedupe #in-place

Last updated on

Spotted something unclear or wrong on this page?

On this page