Coding Interview PatternsRemove Element
EasyTwo Pointers
Remove Element
Explanation & Solution
Description
Given an integer array nums and an integer val, remove all occurrences of val in nums in-place and return the new length. The order of the elements may be changed. It does not matter what you leave beyond the new length.
Input: nums = [3, 2, 2, 3], val = 3
Output: 2
Explanation: The function returns 2, with the first two elements of nums being [2, 2]. The value 3 has been removed.
Constraints
0 <= nums.length <= 1000 <= nums[i] <= 500 <= val <= 100
Approach
Two Pointers pattern
1. Initialize the Slow Pointer
- Set
k = 0to track the write position for non-val elements kwill also represent the final length of the modified array
2. Scan Through the Array
- Use a fast pointer
ito iterate from0tonums.length - 1 - Each element is checked exactly once
3. Keep Non-Matching Elements
- If
nums[i] !== val, the element should be kept - Copy
nums[i]intonums[k]and incrementk - This shifts all non-val elements to the front of the array
4. Skip Matching Elements
- If
nums[i] === val, do nothing - The fast pointer
iadvances, butkstays in place - This effectively overwrites val elements with the next valid one
5. Return the New Length
- After the loop,
kequals the number of elements that are notval - The first
kelements ofnumscontain all the kept values
Key Insight
- The two-pointer technique uses a slow pointer
k(write position) and a fast pointeri(read position) - Every non-val element is written to the front, preserving them while discarding matches
Time
O(n)single pass through the arraySpace
O(1)in-place modification, no extra storageVisualization
Input:
[3, 2, 2, 3], val = 3
—
Press ▶ or use ← → to step through
Pointer iPointer jProcessedDone
7 steps