File tree Expand file tree Collapse file tree 1 file changed +81
-0
lines changed
remove-nth-node-from-end-of-list Expand file tree Collapse file tree 1 file changed +81
-0
lines changed Original file line number Diff line number Diff line change 1+ """
2+ 19. Remove Nth Node From End of List
3+ https://leetcode.com/problems/remove-nth-node-from-end-of-list/
4+ """
5+
6+
7+ from typing import Optional
8+
9+ class ListNode :
10+ def __init__ (self , val = 0 , next = None ):
11+ self .val = val
12+ self .next = next
13+
14+ """
15+ Solution 1:
16+ Two Pass Algorithm 1
17+ - First pass: Count the number of nodes and store the values in the list
18+ - Second pass: Build the new list without the Nth node from the end
19+
20+ Time complexity: O(N)
21+ - Two passes are required
22+ Space complexity: O(N)
23+ - The list stores the values of the nodes
24+ - The new nodes are created to build the new list
25+ """
26+
27+ class Solution1 :
28+ def removeNthFromEnd (self , head : Optional [ListNode ], n : int ) -> Optional [ListNode ]:
29+
30+ vals = []
31+
32+ while head :
33+ vals .append (head .val )
34+ head = head .next
35+
36+ dummy_node = ListNode ()
37+ tail = dummy_node
38+ _n = len (vals ) - n
39+ vals = vals [:_n ] + vals [_n + 1 :]
40+
41+ for v in vals :
42+ tail .next = ListNode (val = v )
43+ tail = tail .next
44+
45+ return dummy_node .next
46+
47+
48+
49+ """
50+ Solution 2:
51+ Reference:
52+ [1] https://leetcode.com/problems/remove-nth-node-from-end-of-list/editorial/
53+ [2] https://www.algodale.com/problems/remove-nth-node-from-end-of-list/
54+ One Pass Algorithm
55+ - Use two pointers to maintain a gap of n nodes between them
56+ - When the first pointer reaches the end, the second pointer will be at the Nth node from the end
57+
58+ Time complexity: O(N)
59+ - Only one pass is required
60+ Space complexity: O(1)
61+ - No extra space is required
62+ """
63+
64+ class Solution2 :
65+ def removeNthFromEnd (self , head : Optional [ListNode ], n : int ) -> Optional [ListNode ]:
66+
67+ dummy = ListNode ()
68+ dummy .next = head
69+ first = dummy
70+ second = dummy
71+
72+ for _ in range (n + 1 ):
73+ first = first .next
74+
75+ while first :
76+ first = first .next
77+ second = second .next
78+
79+ second .next = second .next .next
80+
81+ return dummy .next
You can’t perform that action at this time.
0 commit comments