Skip to content

Instantly share code, notes, and snippets.

@thekhairul
Last active May 23, 2022 05:03
Show Gist options
  • Save thekhairul/0df4673e98e628919319617b30dafaf0 to your computer and use it in GitHub Desktop.
Save thekhairul/0df4673e98e628919319617b30dafaf0 to your computer and use it in GitHub Desktop.
Leetcode 19: Remove Nth Node From End of List - python
def removeNthFromEnd(head,n):
# O(2n) || O(1)
count = 0
cur = head
while cur:
count += 1
cur = cur.next
m = count - n
if m == 0:
# when m is 0, need to remove the head by making the next node head
return head.next
cur = head
count = 1
while cur:
if count == m:
# when cur node is the node before n (count == m), remove the nth node
cur.next = cur.next.next
break
count += 1
cur = cur.next
return head
# fast and slow pointers : O(n) || O(1)
fast = slow = head
for _ in range(n):
fast = fast.next
if not fast:
return head.next
while fast.next:
fast, slow = fast.next, slow.next
slow.next = slow.next.next
return head
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment