Skip to content

Commit 394d5e9

Browse files
committed
solve: removeNthNodeFromEndOfList
1 parent a002894 commit 394d5e9

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
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

0 commit comments

Comments
 (0)