Remove Duplicates from Sorted Array
Last updated
Was this helpful?
Last updated
Was this helpful?
Given a sorted array nums, remove the duplicates such that each element appears only once and returns the new length.
Do not allocate extra space for another array, you must do this by modifying the input array with O(1) extra memory.
Since our array is sorted, we're able to arrive to a O(1)
time solution or circumvent using extra space. We will use a Two-Pointer Technique by having i and j
, each going at different speed and advancing under a certain condition.
Pointer i and j both start at 0
with j moving forward by 1 at each iteration.
When j
encounters a different element (Since array is sorted, j just encountered the next element), move i forward by 1, then overwrite the element that i
is now pointing to after advancing with the element that j
is currently pointing to.
We do this until j reaches the end of the array.
We then return i + 1 as this value will now indicate the number of unique elements that are now in the array.
Time: O(n) Space: O(1)
The below is quite short and it does pass the test however it does not conform to the above specified constraints which is to do it in-place while concurrently making sure that you do not use extra memory.
Time: O(n) Space: O(uniqueElements)