Description

Given the head of a linked list, remove the nth node from the end of the list and return its head.

Example 1:

  • Input: head = [1,2,3,4,5], n = 2
  • Output: [1,2,3,5]

Example 2:

  • Input: head = [1], n = 1
  • Output: []

Example 3:

  • Input: head = [1,2], n = 1
  • Output: [1]

Constraints:

  • The number of nodes in the list is sz.
  • 1 <= sz <= 30
  • 0 <= Node.val <= 100
  • 1 <= n <= sz

Follow up: Could you do this in one pass?

💡 Hint 1:
Maintain two pointers and update one with a delay of n steps.

Submitted Code

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next

class Solution:
    def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
        save = head
        slow, fast = head, head
        for _ in range(n):
            fast = fast.next

        if not fast:            # 노드가 1개인 경우
            return head.next
            
        while fast.next:
            slow = slow.next
            fast = fast.next
        
        slow.next = slow.next.next
        return save

Runtime: 0 ms | Beats 100.00%
Memory: 19.28 MB | Beats 85.01%

fast를 먼저 n칸 보내고 slow와 같이 움직이는 구조로 한 번의 순회만에 풀 수 있다.

Other Solutions

1st

class Solution:
    def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
        dummy = ListNode(0, head)
        first = dummy
        second= dummy

        for _ in range(n + 1):
            first = first.next

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

        second.next = second.next.next
        return dummy.next

time complexity: 𝑂(𝑛)
space complexity: 𝑂(1)

head를 따로 저장하는 것보다 맨 앞에 더미 노드를 생성하는 방법이 훨씬 더 깔끔해서 좋았다.

Leave a comment