Created
May 27, 2020 17:23
-
-
Save pratik7368patil/ac4ce47ace058696478ee10e768f3dd2 to your computer and use it in GitHub Desktop.
Remove Duplicates from array in python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# remove duplicate from array in place | |
# below function returns modified array | |
# time complexity of this program is O(nlogn) + O(n) that is nothing but O(nlogn). | |
def remove_duplicate(arr): | |
arr.sort() # sort array that will take O(nlogn) time | |
l = len(arr) | |
if l == 0 or l == 1: # check for a base condition | |
return arr | |
x = 0 # extra pointer | |
for i in range(0, l-1): | |
if arr[i] != arr[i+1]: | |
arr[x] = arr[i] # shifting element to front of array | |
x += 1 | |
arr[x] = arr[l-1] | |
x += 1 | |
return arr[:x] | |
arr = [10,20,10,10,20,30,40] # original array | |
print(remove_duplicate(arr)) | |
# the output will be [10,20,30,40] | |
# but if you try to print(arr) the output will be [10,20,30,40,20,30,40] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment