Remove Duplicates from Sorted Array I and II
Two Pointers
Problem
Given an array of sorted numbers, remove all duplicates from it. You should not use any extra space; after removing the duplicates in-place return the length of the subarray that has no duplicate in it.
For example:
Thought Process
We can use the two pointer approach where one pointer will be used to iterate through the array and the second pointer will be used to keep track of the position of the place where the next non-duplicate number/unique should be placed.
We will have one pointer for iterating through the array and one pointer for placing the next non-duplcate number.
We will be moving the non-duplicate numbers to the far left since the array is already sorted
The index of our nextNonDuplicate pointer is the potential position that can be filled by a non-duplicate number. This spot cannot be equal/the same number of the previous number in the already sorted non-duplicate portion, so we have to compare the previous number to the element of the current index.
Solution
Follow Up:
Given a sorted array nums, remove the duplicates in-place such that duplicates appeared at most twice and return the new length.
For example:
Key Points
Using two pointers: one to iterate through the array and the other pointer to keep track of the position of the next non-duplicate
The pointer that keeps track of the next non-duplicate position is key for this problem
Time Complexity
Time: O(N)
Space: O(1)
Last updated
Was this helpful?