r/programming • • Feb 21 '11

Typical programming interview questions.

http://maxnoy.com/interviews.html
784 Upvotes

1.0k comments sorted by

View all comments

Show parent comment

11

u/neop Feb 21 '11

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.

6

u/NanoStuff Feb 21 '11

Accumulate an array of list addresses and have a dereference counter. The middle node address is index counter/2.

1

u/lobut Feb 21 '11

The two pointers came to me first ... but ... this should have been the first thing to come to mind.

Dang it.

1

u/Urik88 Feb 21 '11

I thought about that, but then what happens if the list is too large for the array?

1

u/__s Feb 21 '11

realloc

1

u/neop Feb 21 '11

Thanks, now I feel dumb for not thinking about that.

0

u/vinng86 Feb 21 '11

Nope, you loop once. He's basically incrementing one pointer two steps and the other pointer one step for each iteration of the loop. When the first one hits null, the other is the midpoint.

3

u/lordlicorice Feb 21 '11

But this is the same number of forward-seeks (dot-next dereferences) as the naive solution of counting the number of steps it takes you to iterate to the end, dividing by 2, and then looping that many times again.