#27
Remove Element
EasyArrayTwo PointersHash MapArrayTwo Pointers
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution (Two Pointers)★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal approach uses the two pointers technique to efficiently remove elements in-place. One pointer traverses the array while the other keeps track of the position to place the next valid element.
⚙️
Algorithm
4 steps- 1Step 1: Initialize a pointer 'k' to 0, which will track the position of the next valid element.
- 2Step 2: Iterate through the array with another pointer 'i'.
- 3Step 3: If nums[i] is not equal to val, assign nums[k] = nums[i] and increment k.
- 4Step 4: After the loop, k will be the count of elements not equal to val.
solution.py9 lines
1# Full working Python code with comments
2
3def removeElement(nums, val):
4 k = 0 # Pointer for the next valid position
5 for i in range(len(nums)):
6 if nums[i] != val:
7 nums[k] = nums[i] # Place valid element at position k
8 k += 1 # Increment k
9 return k # Return the count of valid elementsℹ
Complexity note: The time complexity is O(n) because we make a single pass through the array, and the space complexity is O(1) since we are modifying the array in place without using additional storage.
- 1Using the two pointers technique allows us to efficiently modify the array in-place without needing extra space.
- 2Understanding that we can overwrite elements in the original array rather than removing them can simplify the problem.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.