## Oracle Interview Question for Software Engineer / Developers

Country: -
Interview Type: In-Person

Comment hidden because of low score. Click to expand.
0
of 0 vote

``````//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){
{
return null;
}else{
while(k > 0 ){
runner = runner.next;
k--;
}
while(runner != null){
runner = runner.next;
target = target.next;
}
return target;

}
}``````

Comment hidden because of low score. Click to expand.
0

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){
if(size < k)
{
return null;
}else{
int count = size - k;
while(count > 0 ){
runner = runner.next;
count--;
}
return runner;

}
}``````

Comment hidden because of low score. Click to expand.
0
of 0 vote

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)

Name:

Writing Code? Surround your code with {{{ and }}} to preserve whitespace.

### Books

is a comprehensive book on getting a job at a top tech company, while focuses on dev interviews and does this for PMs.

### Videos

CareerCup's interview videos give you a real-life look at technical interviews. In these unscripted videos, watch how other candidates handle tough questions and how the interviewer thinks about their performance.