educative.io

Educative

Proposal of subjectively simpler solution. Please provide feedback

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.

Hi @Andrew,

We need to remove the duplicates from the input array, this is a requirement. The problem states that we should remove the duplicates in-place. Since we are changing the input array we don’t need to return the array but we definitely need to know what is the length of the array after removal of duplicates. Which is why we are asked to return the resultant length of the array.

Hope this clarifies your question.

the problem tells us to remove the duplicates, yet the solutions doesn’t do it. it just shifts the elements. the problem statement is wrong, it’s been years and haven’t been corrected.