-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRemoveNthNodefromEndofList_Day44.py
More file actions
65 lines (50 loc) · 1.45 KB
/
RemoveNthNodefromEndofList_Day44.py
File metadata and controls
65 lines (50 loc) · 1.45 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
# Brute Approach
class Solution:
def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
nodes = []
current = head
while current:
nodes.append(current)
current = current.next
index_to_remove = len(nodes) - n
if index_to_remove == 0:
return head.next
prev = nodes[index_to_remove - 1]
prev.next = prev.next.next
return head
# TC - O(2N)
# SC - O(N)
# Better Approach
class Solution:
def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
length = 0
temp = head
while temp:
length += 1
temp = temp.next
if n == length:
return head.next
temp = head
for _ in range(length - n - 1):
temp = temp.next
temp.next = temp.next.next
return head
# TC - O(2N)
# SC - O(1)
# Optimal Approach
class Solution:
def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
dummy = ListNode(0, head)
fast = slow = dummy
# Move fast pointer n steps ahead
for _ in range(n):
fast = fast.next
# Move both pointers until fast reaches the end
while fast.next:
fast = fast.next
slow = slow.next
# Skip the target node
slow.next = slow.next.next
return dummy.next
# TC - O(N)
# SC - O(1)