Given a sorted array nums, remove the duplicates in-place such that each element appear only once and return the new length.
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
Note that the input array is passed in by reference, which means modification to the input array will be known to the caller as well.
You have to return
length of the new array. But, because the array itself is passed by reference the caller knows the new values.
Because we have to sort the array - time complexity would at least be
We can maintain two pointers
- p -> pointing to the last unique element
- i -> pointing to the current element being inspected
And finally return
Sample test cases
This may not be the optimal solution. And that’s okay. The purpose here is to practice problem solving and have fun with algorithms. I am constantly learning new optimized solutions for these problems.
Please comment below if you have a better solution. Let’s learn algorithms and data structures together.