Remove Duplicates from Sorted Array II — LeetCode 80 Python Solution
- Problem
- #80
- Pattern
- Two Pointers
- Reading time
- 2 min
- Source
- leetcode.com
The problem
Given an integer array nums sorted in non-decreasing order, remove some duplicates in-place such that each unique element appears at most twice. The relative order of the elements should be kept the same.
Example
int[] nums = [...]; // Input array
int[] expectedNums = [...]; // The expected answer with correct length
int k = removeDuplicates(nums); // Calls your implementation
assert k == expectedNums.length;
for (int i = 0; i < k; i++) {
assert nums[i] == expectedNums[i];
}Python solution
class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
k = 0
for x in nums:
if k < 2 or x != nums[k - 2]:
nums[k] = x
k += 1
return kComplexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(1) auxiliary |
Pattern: Two Pointers
Use the order already in the input to discard half the search space at every step. LeetCode 80. Remove Duplicates from Sorted Array II 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 80. Remove Duplicates from Sorted Array II?
- LeetCode 80. Remove Duplicates from Sorted Array II is rated Medium on LeetCode.
- What is the time complexity of LeetCode 80. Remove Duplicates from Sorted Array II?
- The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 80. Remove Duplicates from Sorted Array II?
- The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 80. Remove Duplicates from Sorted Array II cover?
- LeetCode 80. Remove Duplicates from Sorted Array II is tagged Array and Two Pointers on LeetCode.