File tree Expand file tree Collapse file tree 1 file changed +29
-0
lines changed
remove-nth-node-from-end-of-list Expand file tree Collapse file tree 1 file changed +29
-0
lines changed Original file line number Diff line number Diff line change
1
+ # Time Complexity: O(N) - go through the list twice (once to count, once to remove).
2
+ # Space Complexity: O(1) - only use a few extra variables.
3
+
4
+ class Solution :
5
+ def removeNthFromEnd (self , head : Optional [ListNode ], n : int ) -> Optional [ListNode ]:
6
+ # count the total number of nodes in the list
7
+ N = 0
8
+ curr = head
9
+ while curr :
10
+ N += 1
11
+ curr = curr .next
12
+
13
+ # find the position of the node to remove (from the start)
14
+ node_to_remove = N - n
15
+
16
+ # if need to remove the first node, just return the second node as the new head
17
+ if node_to_remove == 0 :
18
+ return head .next
19
+
20
+ # traverse again to find the node right before the one we need to remove
21
+ curr = head
22
+ for i in range (N - 1 ):
23
+ if (i + 1 ) == node_to_remove :
24
+ # remove the nth node by skipping it
25
+ curr .next = curr .next .next
26
+ break
27
+ curr = curr .next
28
+
29
+ return head
You can’t perform that action at this time.
0 commit comments