Coding Challenge from Leetcode - Remove Duplicates from Sorted Array!
Here is the problem and solution to a coding challenge from Leetcode.com called 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.
Return k after placing the final result in the first k slots of nums, where k is the number of unique values
Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory.
Update the first k elements in-place with the unique values using a two pointer technique
O(n) where ’n’ is the number of characters of the input array
O(1) only constant space used
Let me know if you have any questions or see ways I could have optimized!
Problem
Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once.
Return k after placing the final result in the first k slots of nums, where k is the number of unique values
Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory.
Solution summary
Intuition / tip
Update the first k elements in-place with the unique values using a two pointer technique
Approach
- Create an “update pointer” for updating the array, initially set to 1 (for index 1; the second item)
- Loop the input array, also starting at the index 1
- For each item in the array
- Check if the previous item is not equal to the current item
- If not, update the item at the update pointer’s index, then increment the update pointer
- Once the loop is finished, return the update pointer (now the number of unique items)
Time complexity
O(n) where ’n’ is the number of characters of the input array
Space complexity
O(1) only constant space used
Let me know if you have any questions or see ways I could have optimized!