I don’t quite get the general idea behind the code, why the array gets one short element in the end just from updating. How does the extra space get removed?
My understanding is that overall we have 2 “pointers” moving in the array, i and write_index. So write_index progresses together with i, and when there’s a duplicate found, write_index will stay behind and “hold” the duplicate. The index i will move forward and find a non duplicate, in which case the if statement will activate once more and update the duplicated element where write_index is, into to the non-duplicate. Is this correct?
But at the end of it, where does the deleting of the element come from? The solution works very well however, so I’m confused.
def delete_duplicates(A): if not A: return 0 write_index = 1 for i in range(1, len(A)): if A[write_index - 1] != A[i]: A[write_index] = A[i] write_index += 1 return write_index