Challenge: Return the Nth Node from End
Returning nth node from the start of a list is easy, but can you return nth node from the end of a list? Solve this challenge and see if your output matches the correct output.
We'll cover the following
Problem Statement #
In this problem, you have to implement Object nthElementFromEnd(SinglyLinkedList<T> list, int n)
method, which will take a linked list as an input and returns the nth element of the list from the end. To solve this, you will have to come up with a formula by comparing multiple outputs and inputs and identifying a common pattern. An illustration is also provided for your understanding.
Method Prototype #
public static <T> Object nthElementFromEnd(SinglyLinkedList<T> list, int n)
Output #
It will return nth node from the end of the linked list.
Sample Input #
linkedlist = 22->18->60->78->47->39->99 and n=3
Sample Output #
47
Consider the following example:
Level up your interview prep. Join Educative to access 70+ hands-on prep courses.