Algorithm Day113 - Remove Element

πŸš€ Day113 - LeetCode 27: Remove Element

πŸ” Problem

Given an integer array nums and an integer val, remove all occurrences of val in nums in-place.
Return the number of remaining elements. Order may change.

🧠 Approach

  • Use two pointers
  • fast scans array
  • slow records valid element positions
  • When nums[fast] != val, copy to nums[slow]

βœ… Complexity

  • Time: O(n)
  • Space: O(1)

πŸ’» Java Code

1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
public int removeElement(int[] nums, int val) {
int slow = 0;
for (int fast = 0; fast < nums.length; fast++) {
if (nums[fast] != val) {
nums[slow] = nums[fast];
slow++;
}
}
return slow;
}
}

πŸ“ Notes

  • We don’t need an extra array
  • Just overwrite values in-place
  • slow pointer gives the new length

Keep grinding β€” one step closer every day! πŸ’ͺπŸ”₯