Problem Link
Detailed Step-by-Step Explanation
Problem in Simple Words
You are given an integer array nums and an integer val.
- Remove all occurrences of
valfrom the array - Do the operation in place
- Order of elements does not matter
- Return the number of elements that are not equal to
val
What the Problem Is Really Asking
You are not asked to resize the array.
You are only asked to:
- Rearrange the array so that all elements not equal to
valcome first - Return how many such elements exist
Everything beyond that index does not matter.
Key Idea
We use two pointers:
-
i→ scans every element -
j→ tracks where the next valid element should go
Whenever we see a value that is not equal to val, we keep it.
Why This Works
- We overwrite only values that are meant to be removed
- All valid elements are packed at the front
- No extra memory is used
Variables Explained
int j = 0;
-
jstores the position where the next valid element should be placed - It also ends up being the final count of valid elements
Step-by-Step Logic
We loop through the array:
for (int i = 0; i < n; i++) {
For every element:
-
If it is not equal to
val- Copy it to index
j - Increment
j
- Copy it to index
-
If it equals
val- Skip it
Full Code
class Solution {
public int removeElement(int[] nums, int val) {
int n = nums.length;
int j = 0;
for (int i = 0; i < n; i++) {
if (nums[i] != val) {
nums[j] = nums[i];
j++;
}
}
return j;
}
}
Example Walkthrough
Input:
nums = [3,2,2,3]
val = 3
Step by step:
- i = 0 → value is 3 → skip
- i = 1 → value is 2 → keep → nums[0] = 2
- i = 2 → value is 2 → keep → nums[1] = 2
- i = 3 → value is 3 → skip
Result:
- First
2elements are valid - Returned value =
2
Why We Return j
-
jcounts how many valid elements were placed - It represents the new length of the array
- Everything after index
j - 1can be ignored
Time and Space Complexity
- Time:
O(n) - Space:
O(1)
Final Takeaway
This problem is about filtering, not deleting.
Once you realize that the array does not need to shrink,
just be rearranged, the solution becomes straightforward and efficient.

Top comments (0)