Remove duplicates from sorted array leetcode solution javascript

Ali Hasan
2 min readJan 17, 2023

--

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.

function removeDuplicates(nums) { if (nums.length === 0) { return 0; } let i = 0; for (let j = 1; j < nums.length; j++) { if (nums[j] !== nums[i]) { i++; nums[i] = nums[j]; } } return i + 1; }

This function uses two pointers, i and j, to iterate through the array. The pointer i is used to keep track of the last unique element, and the pointer j is used to iterate through the rest of the array. If the element at index j is not equal to the element at index i, then it is a unique element, so it is copied to the index i+1 and i is incremented. This way, only unique elements are kept in the first part of the array and the function returns the new length of the array with unique elements.

solution

--

--

Ali Hasan
Ali Hasan

No responses yet