26. Remove Duplicates from Sorted Array
Asked at 23Bloomberg73Microsoft72Meta69Google66Amazon64Apple46tcs70Infosys50Wissen Technology100Capgemini68Accenture66Siemens65Myntra64Deloitte59Cognizant57Morgan Stanley54Cisco51Yandex46Walmart Labs43Zoho42Oracle41IBM35Goldman Sachs21
Problem
Given a sorted array nums, remove the duplicates in place so each value appears once, keeping the original order. Return the number k of unique values; the first k slots of nums must hold them (what's after doesn't matter).
Example: [0,0,1,1,1,2,2,3,3,4] → 5, with nums starting [0,1,2,3,4]
Constraints: O(1) extra space.
Slow pointer k marks the end of the unique prefix; fast pointer scans. Copy whenever a new value appears.
Complexity: O(n) time, O(1) space.
class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
k = 0
for x in nums:
if k == 0 or x != nums[k - 1]:
nums[k] = x
k += 1
return k
a = [0, 0, 1, 1, 1, 2, 2, 3, 3, 4]
k = Solution().removeDuplicates(a)
assert k == 5 and a[:k] == [0, 1, 2, 3, 4]
a = [1, 1, 2]
k = Solution().removeDuplicates(a)
assert k == 2 and a[:k] == [1, 2]
a = [7]
k = Solution().removeDuplicates(a)
assert k == 1 and a[:k] == [7]
class Solution {
public int removeDuplicates(int[] nums) {
int k = 0;
for (int x : nums) if (k == 0 || x != nums[k - 1]) nums[k++] = x;
return k;
}
}
func removeDuplicates(nums []int) int {
k := 0
for _, x := range nums {
if k == 0 || x != nums[k-1] {
nums[k] = x
k++
}
}
return k
}