Skip to content

Commit

Permalink
add solution: remove-nth-node-from-end-of-list
Browse files Browse the repository at this point in the history
  • Loading branch information
dusunax committed Feb 27, 2025
1 parent bb6378c commit 94106fc
Showing 1 changed file with 70 additions and 0 deletions.
70 changes: 70 additions & 0 deletions remove-nth-node-from-end-of-list/dusunax.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
'''
# 19. Remove Nth Node From End of List
## ํ’€์ด ์ ‘๊ทผ๋ฐฉ์‹ ๋ ˆํผ๋Ÿฐ์Šค
- https://www.algodale.com/problems/remove-nth-node-from-end-of-list/
'''
class Solution:
def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
'''
# 1. ๋…ธ๋“œ ๋ฆฌ์ŠคํŠธ
- ์Œ์ˆ˜ ์ธ๋ฑ์Šค ์›์†Œ ์ ‘๊ทผ
- nodes ๋ฐฐ์—ด์„ ์‚ฌ์šฉํ•˜์—ฌ ๋งˆ์ง€๋ง‰ n๋ฒˆ์งธ ๋…ธ๋“œ๋ฅผ ์ฐพ๋Š”๋‹ค.
- ๋ฉ”๋ชจ๋ฆฌ ๋‚ญ๋น„
TC: O(N), SC: O(N)
'''
# nodes = [] # ๋ฐฐ์—ด
# temp = ListNode(None, head)
# node = temp

# while node:
# nodes.append(node)
# node = node.next

# nodes[-n - 1].next = nodes[-n - 1].next.next

# return temp.next

'''
# 2. ํ
- ํ๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ๋งˆ์ง€๋ง‰ n๋ฒˆ์งธ ๋…ธ๋“œ๋ฅผ ์ฐพ๋Š”๋‹ค.
- ์ตœ๋Œ€ n+1๊ฐœ์˜ ๋…ธ๋“œ(ํ•„์š”ํ•œ ๋ฒ”์œ„)๋งŒ ์œ ์ง€, ์Šฌ๋ผ์ด๋”ฉ ์œˆ๋„์šฐ
TC: O(N), SC: O(N)
'''
# queue = deque() #ํ
# temp = ListNode(None, head)
# node = temp

# for _ in range(n + 1):
# queue.append(node)
# node = node.next

# while node:
# queue.popleft()
# queue.append(node)
# node = node.next

# queue[0].next = queue[0].next.next
# return temp.next

'''
# 3. ํฌ์ธํ„ฐ
- ์—ฐ๊ฒฐ ๋ฆฌ์ŠคํŠธ์˜ ํŠน์„ฑ ์ด์šฉ
- ์ฒซ๋ฒˆ์งธ ํฌ์ธํ„ฐ๋Š” n๋ฒˆ ์ด๋™ํ•˜์—ฌ ๋งˆ์ง€๋ง‰ ๋…ธ๋“œ๋ฅผ ์ฐพ๋Š”๋‹ค.
- ๋‘๋ฒˆ์งธ ํฌ์ธํ„ฐ๋Š” ์ฒซ๋ฒˆ์งธ ํฌ์ธํ„ฐ๊ฐ€ ๋งˆ์ง€๋ง‰ ๋…ธ๋“œ๋ฅผ ์ฐพ์„ ๋•Œ๊นŒ์ง€ ์ด๋™ํ•œ๋‹ค.
- ๋‘๋ฒˆ์งธ ํฌ์ธํ„ฐ๋Š” ์ฒซ๋ฒˆ์งธ ํฌ์ธํ„ฐ๊ฐ€ ๋งˆ์ง€๋ง‰ ๋…ธ๋“œ๋ฅผ ์ฐพ์œผ๋ฉด ์ฒซ๋ฒˆ์งธ ํฌ์ธํ„ฐ์˜ ์ด์ „ ๋…ธ๋“œ๋ฅผ ์‚ญ์ œํ•œ๋‹ค.
TC: O(N), SC: O(1)
'''
first = head
for _ in range(n):
first = first.next

temp = ListNode(None, head)
second = temp

while first:
first = first.next
second = second.next

second.next = second.next.next
return temp.next

0 comments on commit 94106fc

Please sign in to comment.