How can you remove duplicates from an array in-place?

Arrays Linked Lists Questions Medium



46 Short 80 Medium 67 Long Answer Questions Question Index

How can you remove duplicates from an array in-place?

To remove duplicates from an array in-place, we can use a two-pointer approach.

First, we initialize two pointers, "i" and "j", both pointing to the second element of the array.

Then, we iterate through the array using the "j" pointer. For each element at index "j", we compare it with the element at index "i-1". If they are equal, we continue incrementing "j" until we find a different element.

Once we find a different element, we copy it to the position "i" and increment both "i" and "j". This process continues until we reach the end of the array.

Finally, we return the subarray from index 0 to "i", which contains the unique elements of the original array.

Here is the implementation in Python:

def remove_duplicates(nums):
if len(nums) == 0:
return 0

i = 1
for j in range(1, len(nums)):
if nums[j] != nums[i-1]:
nums[i] = nums[j]
i += 1

return i

# Example usage
arr = [1, 2, 2, 3, 4, 4, 5]
result = remove_duplicates(arr)
print(arr[:result]) # Output: [1, 2, 3, 4, 5]