Skip to content

Commit c2a03be

Browse files
committed
feat: add remove nth node from end of list solution
1 parent 0a03ea4 commit c2a03be

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
from typing import Optional
2+
3+
4+
# Definition for singly-linked list.
5+
class ListNode:
6+
def __init__(self, val=0, next=None):
7+
self.val = val
8+
self.next = next
9+
10+
11+
class Solution:
12+
def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
13+
"""
14+
- Idea: ๋‘ ํฌ์ธํ„ฐ(slow, fast)๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ slow๊ฐ€ ์‚ญ์ œํ•  ๋…ธ๋“œ์˜ ์ด์ „ ๋…ธ๋“œ์— ์œ„์น˜ํ•˜๋„๋ก ํ•œ๋‹ค.
15+
slow.next๋ฅผ ์กฐ์ •ํ•˜์—ฌ ์‚ญ์ œํ•  ๋…ธ๋“œ๋ฅผ ๊ฑด๋„ˆ๋›ฐ๋„๋ก ํ•œ๋‹ค.
16+
์‚ญ์ œํ•  ๋…ธ๋“œ๊ฐ€ head์ผ ๊ฒฝ์šฐ๋ฅผ ๊ฐ„๋‹จํžˆ ์ฒ˜๋ฆฌํ•˜๊ธฐ ์œ„ํ•ด dummy ๋…ธ๋“œ๋ฅผ ์‚ฌ์šฉํ•œ๋‹ค.
17+
- Time Complexity: O(n). n์€ ๋ฆฌ์ŠคํŠธ์˜ ๋…ธ๋“œ ์ˆ˜.
18+
์ตœ๋Œ€ ์ „์ฒด ๋ฆฌ์ŠคํŠธ๋ฅผ ์ˆœํšŒํ•˜์—ฌ ์‚ญ์ œํ•  ๋…ธ๋“œ๋ฅผ ์ฐพ๊ณ  ์ œ๊ฑฐํ•˜๋ฏ€๋กœ O(n)์ด ์†Œ์š”๋œ๋‹ค.
19+
- Space Complexity: O(1).
20+
dummy ๋…ธ๋“œ์™€ slow, fast ํฌ์ธํ„ฐ๋ฅผ ์œ„ํ•œ ์ƒ์ˆ˜ ๊ณต๊ฐ„๋งŒ ํ•„์š”ํ•˜๋‹ค.
21+
"""
22+
23+
dummy = ListNode(0)
24+
dummy.next = head
25+
slow, fast = dummy, dummy
26+
27+
for _ in range(n + 1):
28+
fast = fast.next
29+
30+
while fast:
31+
slow = slow.next
32+
fast = fast.next
33+
34+
slow.next = slow.next.next
35+
36+
return dummy.next

0 commit comments

Comments
ย (0)