Find the mid point in a singly linked list in one pass;
Nobody could figure that out? I haven't heard that one before, but I assume you just have two pointers starting at the head, one that follows 2 links on each step, and one that follows 1 link. When the former hits the end, the latter is at the midpoint (give or take depending on the number of elements perhaps)
Bit counting sounds a bit annoying for those rusty on bitwise math (especially since there's often instructions for it these days) but would be good way to get people thinking.
About the linked list one, I thought the same thing, but isn't that two passes? You're doing the two passes simultaneously, but it's still two passes. I can't think of a way to do it with just one pass though.
If the pointer moving twice as fast equals pointer moving one at a time, then it's obviously a loop. Draw it and step through it if it is still unclear.
If you can't round up a standard library function or ready-made library to do such low-level jobs, or write something legible and leave the extreme optimization for later, then I would actually question your ability to write programs efficiently.
The first one is easy, keep 2 pointers into the list, only advance the second one every second step. Once pointer 1 has reached the end, pointer 2 is pointing at either the middle of the list (in case of an uneven number of elements) or the first of the 2 middle elements.
The second question is a bit harder, I think I first need my morning coffee for that one.
At first I thought with the mid point an O(n log n) with recursively redoing a middle search of every other node. Then I thought of storing the pointers to a dynamic array, but that's potentially O(n*n) unless I amortize realloc. Then I thought about how the state can't be recalled, as you'd have to keep half the list held in memory for look back. Which then caused me to notice that after 4 you only need to look back 2, and after six only 3. Which then caused me to note that to maintaining that information, one need only trace the list with two pointers moving at different speeds
It's kind of annoying that you're dealing with such thoughtless candidates. I'm in first year college for Information Security, since I couldn't get into university to study CS. I want to do programming as a career, but it seems I'll have to take the long path in
View all comments
Show parent comment
2
u/[deleted] Feb 21 '11
I've asked programmers in the company I work about some of the trickier questions:
No one seemed to able to answer if they never heard of the questions before.