I4G10daysofcodechallenge: My thought process while solving the "remove-duplicates-from-sorted-array" leetcode problem
I started out hoping to implement a solution that uses O(1) space and takes at most O(nlogn) time. My initial thought was to modify the merge sort algorithm to drop duplicates when encountered, by drop I mean swapping it with a value at the back. But like most first pseudocode I experienced some difficulty implementing it or may have made some wrong assumptions as to what I could do, I quickly abandoned this thought because of time.
I ended up implementing a solution that takes O(n) time and uses O(n) space. when the function is called, an array of order n is initialized, next a for loop of range n - 1 begins. In this for loop, all the unique elements of the input array are copied into the new array, this is achieved by copying only when array[i] is not equal to array[i+1]. This way only unique elements are copied to the new list. After the iteration is complete another loop begins to copy these unique values back into the original array(nums)
By the end of this loop, the length of the unique element which is tracked using a variable k is returned and the original array now contains k unique elements occupying the first k positions in the array