27. Remove Element
EasyView on LeetCode
Time: O(n)
Space: O(1)
Advertisement
Intuition
Use two pointers: a slow write pointer k and a fast scan pointer i. Copy nums[i] to nums[k] only when nums[i] != val. This effectively filters out all instances of val in-place.
Algorithm
- 1Initialise k = 0.
- 2For i from 0 to n-1: if nums[i] != val, set nums[k] = nums[i], k++.
- 3Return k.
Example Walkthrough
Input: nums = [3,2,2,3], val = 3
- 1.i=0: 3==val, skip. i=1: 2!=val -> nums[0]=2, k=1.
- 2.i=2: 2!=val -> nums[1]=2, k=2. i=3: 3==val, skip.
Output: k = 2, nums = [2,2,_,_]
Common Pitfalls
- •The remaining elements beyond index k do not matter - only the first k elements are checked.
27.cs
C#
// Approach: Two pointers — swap each non-target element to the write
// position and advance the write pointer.
// Time: O(n) Space: O(1)
public class Solution
{
public int RemoveElement(int[] nums, int val)
{
int n = nums.Length;
int k = 0;
for (int i = 0; i < n; i++)
{
if (nums[i] != val)
{
int temp = nums[k];
nums[k++] = nums[i];
nums[i] = temp;
}
}
return k;
}
}Advertisement
Was this solution helpful?