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 new length of the array.
Because we are interested in the new length of the array and the array is sorted we may just count duplicates:
def remove_duplicates2(arr):
i = 1
duplicates = 0
while(i < len(arr)):
if arr[i - 1] == arr[i]:
duplicates += 1
i += 1
return len(arr) - duplicates
If we need to print an actual array without duplicates we may use generators in Python (or similar feature in other modern languages):
def remove_duplicates2(arr):
i = 1
duplicates = 0
yield arr[0]
while(i < len(arr)):
if arr[i - 1] == arr[i]:
duplicates += 1
else:
yield arr[i]
i += 1
yield "length %s" % (len(arr) - duplicates)
Happy to keep learning and hear your feedback on some thoughts above.