Solution: Return the Nth Node from End
Let’s solve the Return the Nth Node from End problem.
We'll cover the following
Statement
Given the head
of a linked list, return the
Constraints:
The number of nodes in the list is
. Node.value
n
Solution 1: Double iteration
In this solution, we first determine the length of the linked list, and based on this length, we find the position of the
The steps of the algorithm are given below:
We calculate the length of the linked list. For this, we iterate through the list, starting from the
head
, and increment a counter for each node encountered until reaching the end of the list.We initialize a variable,
position
, with, which gives the position of the element from the end of the linked list. Next, we start traversing from the
head
of the linked listposition
times.After traversing the linked list
position
times, we return the data of the current node in the traversal. This node is thenode from the end to be returned from the linked list.
Let’s look at the code for this solution below:
Level up your interview prep. Join Educative to access 70+ hands-on prep courses.