forked from keon/algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdelete_nth.py
More file actions
66 lines (49 loc) · 1.57 KB
/
delete_nth.py
File metadata and controls
66 lines (49 loc) · 1.57 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
"""
Delete Nth Occurrence
Given a list and a number N, create a new list that contains each element
of the original list at most N times, without reordering.
Reference: https://www.geeksforgeeks.org/remove-duplicates-from-an-array/
Complexity:
delete_nth_naive:
Time: O(n^2) due to list.count()
Space: O(n)
delete_nth:
Time: O(n)
Space: O(n)
"""
from __future__ import annotations
import collections
def delete_nth_naive(array: list[int], n: int) -> list[int]:
"""Keep at most n copies of each element using naive counting.
Args:
array: Source list of integers.
n: Maximum number of allowed occurrences per element.
Returns:
New list with each element appearing at most n times.
Examples:
>>> delete_nth_naive([1, 2, 3, 1, 2, 1, 2, 3], 2)
[1, 2, 3, 1, 2, 3]
"""
result = []
for num in array:
if result.count(num) < n:
result.append(num)
return result
def delete_nth(array: list[int], n: int) -> list[int]:
"""Keep at most n copies of each element using a hash table.
Args:
array: Source list of integers.
n: Maximum number of allowed occurrences per element.
Returns:
New list with each element appearing at most n times.
Examples:
>>> delete_nth([1, 2, 3, 1, 2, 1, 2, 3], 2)
[1, 2, 3, 1, 2, 3]
"""
result = []
counts = collections.defaultdict(int)
for element in array:
if counts[element] < n:
result.append(element)
counts[element] += 1
return result