Nth Node from End šŸš€

beginner
11 min

Nth Node from End šŸš€

Welcome to our deep dive into the world of Data Structures and Algorithms! Today, we're going to learn about finding the Nth node from the end of a linked list šŸŽÆ. This is a common interview question and a great exercise to understand linked lists better. Let's get started!

Understanding Linked Lists šŸ“

Before we jump into the main topic, let's quickly review linked lists. A linked list is a linear data structure consisting of nodes where each node points to the next one. Here's a simple example:

python
class Node: def __init__(self, data): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None

The Problem: Finding the Nth Node šŸ’”

Given a linked list and an integer N, the task is to find the node that is Nth from the end. This means we are looking for the second last node when N equals the length of the list minus one, and the next-to-the-last-but-one node when N equals the length of the list minus two, and so on.

Approach: Two Pointers šŸ“

We can solve this problem using the two-pointer technique. We'll move two pointers, fast and slow, through the list. The fast pointer will move N nodes ahead initially, while the slow pointer will traverse the list normally. After moving N steps, we'll have the fast pointer at some node, and the slow pointer at some other node. From this point, we'll move both pointers towards each other until they meet, which will be the Nth node from the end.

Implementation šŸ’”

Here's a complete implementation in Python:

python
def find_nth_node_from_end(head, n): if not head: return None # Initialize two pointers fast = head slow = head # Move fast `n` nodes ahead for _ in range(n): if not fast: return None fast = fast.next # Move both pointers towards each other while fast: fast = fast.next slow = slow.next fast = fast.next if fast else None return slow

Practical Application šŸŽÆ

In a real-world scenario, this algorithm can be useful for data processing, network analysis, or any application where you need to access a specific node based on its position from the end of a linked list.

Quiz Time šŸŽ“

Let's test your understanding!

Quick Quiz
Question 1 of 1

What is the key idea used to solve the problem of finding the Nth node from the end of a linked list?

That's all for today! Practice the implementation and the quiz to reinforce your understanding of finding the Nth node from the end of a linked list. Happy coding! šŸš€šŸ’»šŸŽ‰