Question
Given a linked list, and an input n, write a function that returns the nth-to-last element of the linked list.
eg.
1 2 3 4 5 |
list = 1 -> 2 -> 3 -> 4 -> 5 -> null nthToLast(list, 0) = 5 nthToLast(list, 1) = 4 nthToLast(list, 4) = 1 nthToLast(list, 5) = null |
Once you think that you’ve solved the problem, click below to see the solution.
As always, remember that practicing coding interview questions is as much about how you practice as the question itself. Make sure that you give the question a solid go before skipping to the solution. Ideally if you have time, write out the solution first by hand and then only type it into your computer to verify your work once you've verified it manually. To learn more about how to practice, check out this blog post.
Solution
How was that problem? You can check out the solution in the video below.
Here is the source code for the solution shown in the video (Github):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
// Private node class private class Node { private int value; private Node next; private Node(int value) { this.value = value; } } public Node nthToLast(Node node, int n) { Node curr = node; Node follower = node; // Iterate curr forward by n. If you reach the end of the list then it is // shorter than n, so you can't possible have an nth-to-last node for (int i = 0; i < n; i++) { if (curr == null) return null; curr = curr.next; } // If length is exactly n, the nth-to-last node would be null if (curr == null) return null; // Move both nodes forward in unison until curr is at the end of the list while (curr.next != null) { curr = curr.next; follower = follower.next; } return follower; } |
Did you get the right answer to this coding interview question? Please share your thoughts in the comments below.