Amazon Interview Question

Find nth last number in a singly linked list.

Interview Answers

Anonymous

Jan 3, 2012

Have two pointers with a difference of n. When pointer1 is at head, pointer2 is at element n from the head. Traverse the list moving pointer1 and pointer2 until pointer2 reaches end of the list at which case pointer1 is pointing to element at N from end.

2

Anonymous

Jan 5, 2012

Yes, using two pointers is a good way: public static Node getNthLast(LinkedList ll, int n) { Node node1 = ll.getHead(); Node node2 = node1; int i = 0; while(node1 != null) { node1 = node1.getNext(); if(i >= n) { node2 = node2.getNext(); } i++; } return node2; }

2

Anonymous

Jan 12, 2012

Node node1 = root; Node node2 = node1; while (num-- > 0) { node2 = node2.getNext(); } while(node2 != null) { node1 = node1.getNext(); node2 = node2.getNext(); } System.out.println("\n\n Last 5th number is : " + node1.getValue());

1

Anonymous

Dec 29, 2011

static List returnNode = null;//define as class scope variable //for this recursive call, very last node (null) return 0, and all preceding nodes gets 1+ higher indexes static int FindNthLast(List L, int N) { if (L == null) return 0; else { int nextLastIndex = FindNthLast(L.Next, N); //If we found the Nth last node, we need assign List value to class-scope returnNode if (nextLastIndex + 1 == N) returnNode = L; return 1 + nextLastIndex; } } //after executing FindNthLast(List, N), returnNode.value is the nth last value we are looking for in the List

1

Anonymous

Jan 3, 2012

The problem here is that we can only start from the head to tail. The previous code is one of the solutions. Another non-recursive solution is that reverse that linked list (http://www.mytechinterviews.com/reverse-a-linked-list) then perform a simple scan to get the nth number from the head. I guess the running time for my solution is O(n).

Anonymous

Jan 3, 2012

Traverse twice through the LL. The first pass will return number of elements. The second pass with the number of an element (starting from zero) subtracted from the size of the list will find the Nth element. O(n). Why make it too complicated?