-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRemoveDuplicatesList_Day34.py
More file actions
42 lines (33 loc) · 992 Bytes
/
Copy pathRemoveDuplicatesList_Day34.py
File metadata and controls
42 lines (33 loc) · 992 Bytes
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
#Better Approach
class Solution:
def deleteDuplicates(self, head: Optional[ListNode]) -> Optional[ListNode]:
if not head:
return None
# Collect values
seen = []
current = head
while current:
if current.val not in seen:
seen.append(current.val)
current = current.next
# Reconstruct new list
dummy = ListNode(-1)
tail = dummy
for val in seen:
tail.next = ListNode(val)
tail = tail.next
return dummy.next
# TC - O(N)
# SC - O(N)
#Optimal Approach
class Solution:
def deleteDuplicates(self, head: Optional[ListNode]) -> Optional[ListNode]:
current = head
while current and current.next:
if current.val == current.next.val:
current.next = current.next.next # Skip duplicate okk
else:
current = current.next
return head
# TC - O(N)
# SC - O(1)