TGViewer
پایتون | Data Science | Machine Learning پایتون | Data Science | Machine Learning @python4all_pro · 24.2K subscribers
Post #732 4.41K
حل سوالات استخدامی سایت leetcode.com

Problem: No. 19. Remove Nth Node From End of List #medium

Condition:
Given the header of a linked list, remove the nth node from the end of the list and return its header

Solution:
# class ListNode:
# def init(self, x):
# self.val = x
# self.next = None

class Solution:
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
if head.next == None:
return None
tmp = head
size = 0

# find the size of the linked list
while tmp:
size += 1
tmp = tmp.next
tmp = head

#if we have to remove the first node:
if n == size:
return head.next

for i in range(size-n-1):
tmp = tmp.next
tmp.next = tmp.next.next
return head



Explanation:
Determining the list size:

First we go through the entire list to find its size. This is necessary to determine which node needs to be removed.
The size variable keeps track of the number of nodes in the list.
Removing the first node:

If n is equal to the size of the list, it means the first node should be removed. In this case, we return the next node from the head of the list.
Search for a node before the one you want to delete:

If n is not equal to the size of the list, we need to find the node that comes before the nth node from the end. We do this by moving size-n-1 nodes forward in the list.
Removing a node:

We set the next node for the found node so that it points to the next node after the next one, effectively bypassing the node to be deleted.
Returning a new header:

Returning the head of the list. If the first node was deleted, the new header will be the starting node of the list after the delete.
Time and space complexity:
Time complexity: O(L), where L is the length of the list. We go through the list twice: once to count nodes and again to remove a node.
Space complexity: O(1) because we use a constant amount of extra space independent of the size of the input data.

#Code
#interview #LeetCode


🆔 @Python4all_pro
  • ❤ 3
  • 👍 3
More from @python4all_pro
  1. Oct 3, 2026🟣کتاب Oxford word skills یک بار جایزه بهترین کتاب آموزش زبان انگلیسی سال را دریافت کرده.…
  2. Oct 2, 2026💥 ۲۰۰ هزار تومان تخفیفِ بیشتر علاوه بر تخفیفِ ۷۵ درصدی موجود در سایت | اشتراک یک ساله فرا…
  3. Sep 29, 2026What better way to understand a powerful tool like Claude Code than to build your own vers…
  4. Sep 28, 2026🧨 ۲۰۰ آموزش جدید دیگر، جایگزین آموزش‌های قبلی شد... 💯 ۴۰۰+۲۰۰ آموزش در فرادرس، هر آموزش…
  5. Sep 28, 202625 GitHub Repositories Every Python Developer Should Know! Want to improve your Python ski…
  6. Sep 27, 202640+ FREE Python Books from Amazon! Want to improve your Python skills without spending a f…
Threads Profile ViewerView any public Threads profile without an account.Open ThreadLook →Writing with AI? Make it sound human.Metric37 rewrites AI drafts so they read naturally. Free AI detector, 1,500 words free.Try Metric37 →