Skip to content

Instantly share code, notes, and snippets.

@pallabpain
Created August 15, 2020 12:58
Show Gist options
  • Save pallabpain/f9d48d6d86ff4f3331a9b59a6144b6a0 to your computer and use it in GitHub Desktop.
Save pallabpain/f9d48d6d86ff4f3331a9b59a6144b6a0 to your computer and use it in GitHub Desktop.
Given a sorted array, remove the duplicates from the array in-place such that each element appears at most twice, and return the new length.
"""
Given a sorted array, remove the duplicates from the array in-place such that each element appears at most twice, and return the new length.
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
Example
Given array [1, 1, 1, 3, 5, 5, 7]
The output should be 6, with the first six elements of the array being [1, 1, 3, 5, 5, 7]
"""
def remove_dup(arr):
n = len(arr)
j = 0
for i in range(n):
if i < n - 2 and arr[i] == arr[i + 2]:
continue
arr[j] = arr[i]
j += 1
return j
arr = [0, 0, 1, 1, 1, 1, 2, 2, 3]
print("OK" if remove_dup(arr) == 7 else "FAILED")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment