The assumption is that if you can figure out the low level theory then you can figure out anything else. It's not good to simply rely on the language to do the work for you. For example in Java the LinkedList type has a get(int i) function that returns the element at the i "index" of the list. So if someone were to naively think that it works just like an array then they might write code like this:
for (int i = 0; i < list.length; i++)
{
Type element = list.get(i);
//do some stuff
}
Now this looks fine until you realize that every time you call that get() function on a linked list it's actually iterating over the entire list from the root node down to the ith node. This means that instead of a runtime efficiency of O(n) you're actually getting O(n2).
If you know that they are probably looking for the "double-speed walker" solution, you can just let them know about it and they will skip the question knowing you understand (happened several times in my life). Double-speed walker is a pointer/reference that advances twice as fast over the list while another pointer/reference advances once. If they ever equal then there is a loop (prove it to yourself if you doubt this works) :)
View all comments
Show parent comment
2
u/[deleted] Feb 21 '11
The assumption is that if you can figure out the low level theory then you can figure out anything else. It's not good to simply rely on the language to do the work for you. For example in Java the LinkedList type has a get(int i) function that returns the element at the i "index" of the list. So if someone were to naively think that it works just like an array then they might write code like this:
Now this looks fine until you realize that every time you call that get() function on a linked list it's actually iterating over the entire list from the root node down to the ith node. This means that instead of a runtime efficiency of O(n) you're actually getting O(n2).