THN Interview Prep

27. Remove Element

At a Glance

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

Problem (one-liner)

Given integer array numbers and value remove, remove all instances of remove in-place with order preserved for remaining elements. Return the new length keptCount; first keptCount elements are the retained values in original relative order.

Recognition Cues

  • "Remove all occurrences of value", "in-place", relative order
  • Two pointers: writer for kept region, reader scans all

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 — shift left on each hit — O(n²) worst case.
  • Better — count removals then second pass — two scans.
  • Optimal — single pass swap-or-assign writer — O(n) time / O(1) space.

Optimal Solution

Go

package main

func removeElement(numbers []int, remove int) int {
	writeIndex := 0
	for scanIndex := 0; scanIndex < len(numbers); scanIndex++ {
		if numbers[scanIndex] != remove {
			numbers[writeIndex] = numbers[scanIndex]
			writeIndex++
		}
	}
	return writeIndex
}

JavaScript

function removeElement(numbers, remove) {
	let writeIndex = 0;
	for (let scanIndex = 0; scanIndex < numbers.length; scanIndex++) {
		if (numbers[scanIndex] !== remove) {
			numbers[writeIndex] = numbers[scanIndex];
			writeIndex++;
		}
	}
	return writeIndex;
}

Walkthrough

numbers = [3,2,2,3], remove = 3

scanIndexvaluewriteIndexaction
030skip (equals remove)
120write 2 at 0, writeIndex → 1
221write 2 at 1, writeIndex → 2
332skip

Prefix [2,2], length 2.

Edge Cases

  • No matches → return full length.
  • All match → return 0.
  • Empty array → 0.

Pitfalls

  • Using extra array when in-place required.
  • Confusing stable vs unstable removal when order not required (problem asks preserve order).

Similar Problems

Variants

  • Remove duplicates unsorted — hash set or sort first.
  • Remove range of indices.

Mind-Map Tags

#two-pointers #in-place #filter #arrays

Last updated on

Spotted something unclear or wrong on this page?

On this page