I recently have given a coding test in a reputable IT company. There were three coding questions.
They refused me by saying that
as we felt they didn't demonstrate the level of technical depth we're seeking from candidates
Please help me understanding what type of the technical depth my solution is missing? Thanks
Question 2 : Missing level of technical depth (Flatten Tree)
Question 3 : Missing level of technical depth (Common Ancestor)
and this is the 1st question.
Question 1:
Reimplement this code so that its results will always be the same, but that it does not cause a stack overflow on large inputs. Your solution must still implement the Folder interface.
Answer 1:
package iteration;
import java.util.Queue;
public interface Folder<T, U>
{
U fold(U u, Queue<T> list, Function2<T,U,U> function);
}
package iteration;
public interface Function2<T, U, R>
{
R apply(T t, U u);
}
package iteration;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Queue;
public class MyFolder<T, U> implements Folder<T, U>
{
public U fold(U u, Queue<T> ts, Function2<T, U, U> fun) {
if(u == null || ts == null || fun == null)
throw new IllegalArgumentException();
if (ts.isEmpty()) {
return u;
}
//get an iterator first instead of forEach loop, because poll() is modifying underlying collection/queue
Iterator<T> iter = ts.iterator();
while (iter.hasNext()) { //loop over the items
u = fun.apply( ts.poll() , u);
}
return u;
}
public static void main(String[] args) {
Folder<Integer,Integer> folder = new MyFolder<Integer, Integer>();
Queue<Integer> q = new LinkedList<Integer>();
for(int lop =0; lop < 1000000; lop++ ){ //add some values in the Queue
q.add(lop);
}
Integer result = folder.fold(0, q, new Function2<Integer, Integer, Integer>() {
public Integer apply(Integer val1, Integer val2) {
return val1 + val2;
}
});
System.out.println("Result: " + result);
}
}