Remove Duplicates from Sorted Array
EasyGiven a sorted array nums, remove the duplicates in-place such that each unique element appears only once. Return the number of unique elements. The relative order of elements should be kept the same.
Examples
| Input | Output |
|---|---|
| nums = [1,1,2] | 2, nums = [1,2,_] |
| nums = [0,0,1,1,1,2,2,3,3,4] | 5, nums = [0,1,2,3,4,_,_,_,_,_] |
Python Solution
def remove_duplicates(nums: list[int]) -> int:
if not nums:
return 0
write = 1
for read in range(1, len(nums)):
if nums[read] != nums[read - 1]:
nums[write] = nums[read]
write += 1
return writeJavaScript Solution
function removeDuplicates(nums) {
if (!nums.length) return 0;
let write = 1;
for (let read = 1; read < nums.length; read++) {
if (nums[read] !== nums[read - 1]) {
nums[write++] = nums[read];
}
}
return write;
}Step-by-Step Explanation
- Use two pointers: read scans the array, write is where we place the next unique element.
- When we see a new value (different from previous), copy it to write and increment write.
- Return write as the count of unique elements.
Complexity Analysis
| Time | O(n) |
| Space | O(1) |
Tags
ArrayTwo Pointers
Related Problems
Related Tools
All Problems
Two SumReverse a StringPalindrome CheckFizzBuzzBinary SearchReverse Linked ListMerge Two Sorted ArraysValid ParenthesesMaximum Subarray (Kadane's Algorithm)Nth Fibonacci NumberValid AnagramFirst Unique CharacterClimbing StairsRoman to IntegerBest Time to Buy and Sell StockContains DuplicateMove ZeroesIntersection of Two ArraysLongest Common Prefix