LeetCode Problem Workspace
Remove Element
Remove Element challenges you to remove a value from an array in-place using efficient two-pointer scanning and tracking.
2
Topics
9
Code langs
3
Related
Practice Focus
Easy · Two-pointer scanning with invariant tracking
Answer-first summary
Remove Element challenges you to remove a value from an array in-place using efficient two-pointer scanning and tracking.
Ace coding interviews with Interview AiBoxInterview AiBox guidance for Two-pointer scanning with invariant tracking
In the 'Remove Element' problem, you are tasked with removing all instances of a specific value from an array in-place. Using a two-pointer approach, you can modify the array without allocating extra space. The main goal is to keep the array compact and return the number of valid elements left, avoiding the unnecessary movement of elements after the array is shortened.
Problem Statement
Given an integer array nums and an integer val, you need to remove all occurrences of val in nums in-place. The order of the elements may be changed, and you should return the number of elements in nums that are not equal to val.
The problem specifically requires modifying the array in-place. You must return the count of elements that do not equal val, and you are allowed to leave elements beyond this point unchanged. The challenge emphasizes the use of the two-pointer technique for efficiency.
Examples
Example 1
Input: See original problem statement.
Output: See original problem statement.
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]; }
Example 2
Input: nums = [3,2,2,3], val = 3
Output: 2, nums = [2,2,_,_]
Your function should return k = 2, with the first two elements of nums being 2. It does not matter what you leave beyond the returned k (hence they are underscores).
Example 3
Input: nums = [0,1,2,2,3,0,4,2], val = 2
Output: 5, nums = [0,1,4,0,3,_,_,_]
Your function should return k = 5, with the first five elements of nums containing 0, 0, 1, 3, and 4. Note that the five elements can be returned in any order. It does not matter what you leave beyond the returned k (hence they are underscores).
Constraints
- 0 <= nums.length <= 100
- 0 <= nums[i] <= 50
- 0 <= val <= 100
Solution Approach
Two-Pointer Technique
Use two pointers to traverse the array. One pointer scans the array, and the other tracks where valid elements (those not equal to val) should be placed. The scanning pointer moves through all elements, and the valid elements are placed in the position tracked by the second pointer.
In-Place Array Modification
Since the problem requires modifying the array in-place, avoid using extra space like new arrays. By adjusting the positions of elements directly within the array, you ensure optimal space complexity and adhere to the problem's constraints.
Return the New Length
After processing the array, return the number of elements in the modified array that are not equal to val. This will be the position of the second pointer, which marks where the valid elements end.
Complexity Analysis
| Metric | Value |
|---|---|
| Time | Depends on the final approach |
| Space | Depends on the final approach |
The time complexity of this approach is O(n), where n is the length of the array, since both pointers traverse the array once. The space complexity is O(1), as the array is modified in-place without using extra storage for elements.
What Interviewers Usually Probe
- Is the candidate able to implement an in-place algorithm that avoids extra space usage?
- Does the candidate use a two-pointer approach efficiently to solve the problem?
- Is the candidate aware of how to handle edge cases, such as when the array is empty?
Common Pitfalls or Variants
Common pitfalls
- Misunderstanding the requirement to modify the array in-place, resulting in unnecessary space allocation.
- Incorrectly updating the array while traversing it, which can lead to overwriting values before they are used.
- Failing to properly track the position of the second pointer, leading to an incorrect final count.
Follow-up variants
- Remove all occurrences of multiple values in the array.
- Remove values from a sorted array while maintaining the sorted order.
- Implement the solution using a single pointer, modifying the array at the current index.
FAQ
How can I use the two-pointer approach to solve the Remove Element problem?
The two-pointer technique helps by using one pointer to scan the array and another to track the position for valid elements. As you scan the array, you move valid elements to the tracked position and increment the second pointer.
What should I do when the element is not found in the array?
If the element to remove is not found, the array remains unchanged, and the length of the array is returned as is.
Can I use additional space to solve the problem?
No, the problem explicitly requires modifying the array in-place, which means you cannot allocate additional space for a new array.
What is the time complexity of this solution?
The time complexity is O(n), where n is the length of the array, as you only traverse the array once.
How do I handle an empty array in the Remove Element problem?
An empty array is a valid input. In this case, the return value will be 0, as there are no elements to remove.
Solution
Solution 1: One Pass
We use the variable $k$ to record the number of elements that are not equal to $val$.
class Solution:
def removeElement(self, nums: List[int], val: int) -> int:
k = 0
for x in nums:
if x != val:
nums[k] = x
k += 1
return kContinue Practicing
Continue Topic
array
Practice more edge cases under the same topic.
arrow_forwardauto_awesomeContinue Pattern
Two-pointer scanning with invariant tracking
Expand the same solving frame across more problems.
arrow_forwardsignal_cellular_altSame Difficulty Track
Easy
Stay on this level to stabilize interview delivery.
arrow_forward