Oracle Interview Question
Software Engineer / DevelopersCountry: -
Interview Type: In-Person
Wouldn't it be simpler just to subtract k from size of head to reduce the number of calls?
Like so:
//Implement an algorithm to find the nth to last element of a singly linked list.
// complexity O (2n) since size(head) requires O ( n )
public static LNode kth(LNode head, int k){
int size = size(head);
if(size < k)
{
return null;
}else{
int count = size - k;
LNode runner = head;
while(count > 0 ){
runner = runner.next;
count--;
}
return runner;
}
}
We can also follow this approach.
Approach 1:
1.Traverse the singly linked list till last and insert each element to the stack.
2. While traversing the element calculate the length of linked list.
3. At the end find the nth element from last using this formula. lets say length of linked list is L and stack is S
So the nth element from last will be S[(L-n+1)] i.e. element in stack S at possition L-n+1.
Note : This approach having space complexity issue. i.e. it will take O(n) space.
Approach 2 :
Another approach find length of linked list and find the L-N+1 th element of linked list from beginning.
both algorithm having time complexity O(n)
- .·´¯`·.´¯`·.¸¸.·´¯`·.¸><(((º> January 28, 2014