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.
How GhostInterview Helps
- GhostInterview walks you through the two-pointer technique to help you solve the problem efficiently.
- It offers tips on handling in-place modifications and the challenges of avoiding extra space.
- You can practice edge cases and optimize your approach for both time and space complexity.
Topic Pages
Related GhostInterview Pages
- LeetCode Interview Copilot - Use GhostInterview as a live solver when you want direct help with LeetCode-style coding questions.
- Coding Interview Assistant - See how GhostInterview supports array, string, linked list, graph, and tree interview workflows.
- How GhostInterview Works - Review the screenshot, reasoning, and answer flow before using the solver in a live interview.
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.
Need direct help with Remove Element instead of spending more time grinding it?
Download GhostInterview when you want a LeetCode solver, not another long practice loop. Capture Remove Element from a screenshot, get the answer path and complexity, and use supported stealth workflows that stay outside captured layers.
Capture the prompt fast instead of rewriting the problem by hand.
Get the solution path, trade-offs, and complexity summary in one pass.
Stay outside captured layers on supported screen-share workflows.
Stay in the same pattern family
Learn how to remove duplicates from a sorted array in-place using two-pointer scanning while preserving element order.
Open problem page#31 Next PermutationNext Permutation is a medium-difficulty problem focusing on generating the next lexicographically greater permutation of integers.
Open problem page#18 4SumThe 4Sum problem requires finding all unique quadruplets in an array that sum to a specific target value.
Open problem page