Coding Challenge from Leetcode - Remove Duplicates from Sorted Array!

Kelvin Graddick · 1 minute read ·     
Here is the problem and solution to a coding challenge from 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.

Solution summary

Intuition / tip

Update the first k elements in-place with the unique values using a two pointer technique


  1. Create an “update pointer” for updating the array, initially set to 1 (for index 1; the second item)
  2. Loop the input array, also starting at the index 1
  3. For each item in the array
  4. Check if the previous item is not equal to the current item
  5. If not, update the item at the update pointer’s index, then increment the update pointer
  6. 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!

Want to share this?