Remove Element
Easy · Two Pointers · Array · Two Pointers
Problem
You are given an integer array nums and an integer val. Remove every occurrence of val from nums in place and return k, the number of values that remain.
After your function returns, the first k slots of nums must hold exactly the values that are not equal to val, in any order. Whatever sits from index k on does not matter. Do not allocate a second array.
The grader checks k and the multiset of nums[:k]; the examples show the kept values sorted.
Examples
Input: nums = [4,1,4,2,4], val = 4 Output: k = 2, nums[:k] = [1,2]
Three 4s are removed, leaving 1 and 2 in the first two slots.
Input: nums = [7,7], val = 7 Output: k = 0, nums[:k] = []
Every value equals val, so nothing is kept.
Input: nums = [3,5,6], val = 1 Output: k = 3, nums[:k] = [3,5,6]
No value equals 1, so all three stay.
Constraints
- 0 <= len(nums) <= 100
- 0 <= nums[i] <= 50
- 0 <= val <= 100
Approaches
- Baseline: shift left over every match — time O(n²), space O(1)
Follow-up
The write cursor keeps the kept values in their original order, which the problem does not require. When val is rare, swap each match with the current last element and shrink the length instead: every kept value stays where it is and only matches cause writes. Other languages grade only k in this problem; the Python grader also checks the kept values.
Related problems
Start free on Cariara · Coding problems · System design studio