Problem
Given an integer array nums and an integer val, remove all occurrences of val in nums in-place. The order of the elements may be changed. Then return the number of elements in nums which are not equal to val.
Consider the number of elements in nums which are not equal to val be k, to get accepted, you need to do the following things:
Change the array nums such that the first k elements of nums contain the elements which are not equal to val. The remaining elements of nums are not important as well as the size of nums.
Return k.
Custom Judge:
The judge will test your solution with the following code:
int[] nums = [...]; // Input array
int val = ...; // Value to remove
int[] expectedNums = [...]; // The expected answer with correct length.
// It is sorted with no values equaling val.
int k = removeElement(nums, val); // Calls your implementation
assert k == expectedNums.length;
sort(nums, 0, k); // Sort the first k elements of nums
for (int i = 0; i < actualLength; i++) {
assert nums[i] == expectedNums[i];
}
If all assertions pass, then your solution will be accepted.
Code
public int RemoveElement(int[] nums, int val) {
int k = 0;
for (int i = 0; i < nums.Length; i++) {
if (nums[i] != val) {
nums[k++] = nums[i];
}
}
return k;
}
Approach
I found the wording of the problem on this one a little confusing but once I'd fully understood the custom judging, I managed to solve it.
The solution uses a two-pointer overwrite technique to remove all occurrences of val in-place:
- Pointer k tracks the position of the next valid element.
Iterate through the array:
- If nums[i] is not equal to val, copy it to nums[k] and increment k.
- Return k as the count of elements not equal to val.
Note: it's important to know [k++]
works by accessing nums[k]
first then incrementing k++
straight after, which is key to how this works.
Key Mechanics
Overwrites unwanted values instead of shifting elements repeatedly.
Maintains only the first k elements as valid; remaining positions can be ignored.
Example
nums = [3,2,2,3], val = 3
Step 1: i=0 → skip (3 == 3)
Step 2: i=1 → nums[0] = 2 (k=0→1)
Step 3: i=2 → nums[1] = 2 (k=1→2)
Step 4: i=3 → skip (3 == 3)
Result: k = 2, nums = [2,2,*,*]
Iteration 0: i = 0
nums[i] = 3
3 == val → skip (do not overwrite, do not increment k)
Iteration 1: i = 1
nums[I] = 2
2 !=2 val → copy nums[i] to nums[k] - overwriting the previous incorrect number
As always if you wish to see more articles like this, drop me a follow on DevTo or twitter/x
Top comments (0)