InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Arrays & Hashing

Remove Element

easy Original ↗ 00:00

Problem

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

Do not allocate a second array. Use 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

Target: one pass, O(1) extra space.

Think about it first

Hint 1 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.)

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug