Skip to content

Commit 1bd6670

Browse files
Optimize remove_duplicates from O(n²) to O(n) time complexity
Use a set for O(1) membership checks instead of checking membership in a list which is O(n). This reduces the overall time complexity from O(n²) to O(n). Added documentation for time and space complexity. Co-Authored-By: Keon <kwk236@gmail.com>
1 parent 5b63e90 commit 1bd6670

File tree

1 file changed

+7
-2
lines changed

1 file changed

+7
-2
lines changed

algorithms/arrays/remove_duplicates.py

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,13 +6,18 @@
66
77
Input: [1, 1 ,1 ,2 ,2 ,3 ,4 ,4 ,"hey", "hey", "hello", True, True]
88
Output: [1, 2, 3, 4, 'hey', 'hello']
9+
10+
Time Complexity: O(n) where n is the length of the input array
11+
Space Complexity: O(n) for the seen set and result array
912
"""
1013

1114
def remove_duplicates(array):
15+
seen = set()
1216
new_array = []
1317

1418
for item in array:
15-
if item not in new_array:
19+
if item not in seen:
20+
seen.add(item)
1621
new_array.append(item)
1722

18-
return new_array
23+
return new_array

0 commit comments

Comments
 (0)