Remove Duplicates from Sorted Array

Leetcode practice log

Posted by Rui on 06-10-2021
Estimated Reading Time 2 Minutes
Words 408 In Total
Viewed Times

Remove Duplicates from Sorted Array

Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same.

Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements.

Return k after placing the final result in the first k slots of nums.

Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory.

Example 1:

Input: nums = [1,1,2]
Output: 2, nums = [1,2,_]
Explanation: Your function should return k = 2, with the first two elements of nums being 1 and 2 respectively.
It does not matter what you leave beyond the returned k (hence they are underscores).

First Try

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/**
* @param {number[]} nums
* @return {number}
*/
var removeDuplicates = function(nums) {
let k = nums.length;
for (let i=1;i<=k-1;){
if (nums[i]==nums[i-1]){
nums.splice(i,1);
k= nums.length;
i--;
}
i++;
}
};

Runtime: 156 ms, faster than 22.39% of JavaScript online submissions for Remove Duplicates from Sorted Array.
Memory Usage: 42.3 MB, less than 11.73% of JavaScript online submissions for Remove Duplicates from Sorted Array.

Feedback and improve

When doing splice, it is an O(n) operation, and because it is in a for loop, it becomes O(n^2).so this solution doesn’t technically meet the requirements.

Improve:
Set nums[0] as first output element, go throgh the next compared to nums[0], move the first element that is different with nums[0] to nums[1], then go through next compared to nums[1] untill we find the next “chosen” nums[2]…

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
var removeDuplicates = function(nums) {
if(nums.length === 0) {
return 0
}
let result = 1, i = 0, j = 1;

while(i < nums.length && j < nums.length) {
if(nums[j] === nums[i]) {
j++;
} else {
result += 1;
i++;
nums[i] = nums[j];
j++;
}
}

return result;
};


If you like this blog or find it useful for you, you are welcome to comment on it. You are also welcome to share this blog, so that more people can participate in it. If the images used in the blog infringe your copyright, please contact the author to delete them. Thank you !