80. Remove Duplicates from Sorted Array II
Asked at 9Amazon49Meta41Google41Bloomberg39Microsoft35Wissen Technology100FreshWorks81Accolite55TikTok26
Problem
nums is sorted. Remove duplicates in place so each value appears at most twice, keeping the order, and return the new length k.
Example: [0,0,1,1,1,1,2,3,3] → 7, with nums starting [0,0,1,1,2,3,3]
Constraints: O(1) extra space.
Allow at most two copies: keep x if k < 2 or x != nums[k-2] (compare with the element two slots back in the kept prefix).
Complexity: O(n).
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 k
a = [0, 0, 1, 1, 1, 1, 2, 3, 3]
k = Solution().removeDuplicates(a)
assert a[:k] == [0, 0, 1, 1, 2, 3, 3]
a = [1, 1, 1, 2, 2, 3]
k = Solution().removeDuplicates(a)
assert k == 5 and a[:k] == [1, 1, 2, 2, 3]
class Solution {
public int removeDuplicates(int[] nums) {
int k = 0;
for (int x : nums) if (k < 2 || x != nums[k - 2]) nums[k++] = x;
return k;
}
}
func removeDuplicates(nums []int) int {
k := 0
for _, x := range nums {
if k < 2 || x != nums[k-2] { // at most two copies
nums[k] = x
k++
}
}
return k
}