Remove Element — LeetCode 27 Python Solution
- Problem
- #27
- Pattern
- Two Pointers
- Reading time
- 2 min
- Source
- leetcode.com
The problem
Given an integer array nums and an integer val, remove all occurrences of val in nums in-place. The order of the elements may be changed.
Example
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];
}Python solution
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 kComplexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(1), where n is the length of the array nums auxiliary |
Pattern: Two Pointers
Use the order already in the input to discard half the search space at every step. LeetCode 27. Remove Element is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Two Pointers.
The two pointers guide has the Python template for the pattern and the 201 LeetCode problems that use it.
Related problems
On a study list
This problem is on Top Interview 150.
Frequently asked questions
- How hard is LeetCode 27. Remove Element?
- LeetCode 27. Remove Element is rated Easy on LeetCode.
- What is the time complexity of LeetCode 27. Remove Element?
- The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 27. Remove Element?
- The Python solution on this page uses O(1), where n is the length of the array nums auxiliary space.
- What topics does LeetCode 27. Remove Element cover?
- LeetCode 27. Remove Element is tagged Array and Two Pointers on LeetCode.