Skip to content

Commit 16f7887

Browse files
committed
solve : remove nth node from end of list
1 parent bb98228 commit 16f7887

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
# TC : O(n)
2+
# SC : O(1)
3+
class Solution:
4+
def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
5+
# Create a dummy node to handle edge cases such as removing the first node
6+
dummy = ListNode(0, head)
7+
left = dummy
8+
right = head
9+
10+
# Move the right pointer n steps ahead
11+
for _ in range(n):
12+
right = right.next
13+
14+
# Move both pointers until right reaches the end
15+
while right:
16+
left = left.next
17+
right = right.next
18+
19+
# Remove the nth node from the end
20+
left.next = left.next.next
21+
22+
# Return the head of the modified list
23+
return dummy.next

0 commit comments

Comments
 (0)