InterviewPrepKit

Home / Coding / Arrays & Hashing

Remove Element

easy Original β†—
Solving tips
  • Recognize in-place filtering: never delete (which shifts the tail), just compact the keepers to the front with a read/write two-pointer.
  • Sweep a read pointer over the array, copy each non-val element to a write pointer w that advances only on keeps, and return w as k; O(n) time, O(1) space.
  • When removals are rare, the swap-with-last variant overwrites each offender with the array's last element and shrinks the end β€” writes equal removals, not keepers.
  • Pitfall: in the swap-with-last variant do NOT advance i after a swap, since the pulled-in element is unexamined and may also equal val; return k, not the array.

Problem

Given an integer array nums and a value val, remove every occurrence of val in place and return k, the number of elements that remain. After your function runs, the first k slots of nums must hold the surviving elements (in any order); whatever sits beyond index k-1 is ignored by the judge.

You may not allocate a second array β€” the point is O(1) extra memory.

Examples

  • Input: nums = [3, 2, 2, 3], val = 3 β†’ Output: k = 2, nums starts with [2, 2] Both 3s are removed; the two 2s remain in the first two slots.
  • Input: nums = [0, 1, 2, 2, 3, 0, 4, 2], val = 2 β†’ Output: k = 5, first five slots are a permutation of [0, 1, 3, 0, 4] Three 2s are removed; order of the keepers is free.
  • Input: nums = [2], val = 3 β†’ Output: k = 1, nums starts with [2] Nothing to remove.

Constraints

  • 0 <= len(nums) <= 100
  • 0 <= nums[i] <= 50
  • 0 <= val <= 100

One pass, O(1) extra space is the target.

Think about it first

Hint 1 Actually deleting from the middle of an array shifts everything after it. What could you do instead of deleting?
Hint 2 Keep a "write" position. As a "read" position sweeps the array, when should the write position advance?
Hint 3 Two pointers: for each element not equal to `val`, copy it to index `w` and increment `w`. At the end `w` is `k`. (If removals are expected to be *rare*, a variant swaps offenders with the last element and shrinks the array instead β€” each element is moved at most once.)
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.