Hacker News new | ask | show | jobs
by tung 5623 days ago
> "Given an infinitely long linked list which you can only traverse once select a random item with O(1) storage."

My shot: pick some random number, go through that many linked list items and return the item you're at. Only needs to store the current item pointer and the random number. Maybe I'm missing something simple, though to be fair, it's a lot harder to answer these kinds of questions when you're under the scrutiny of an interview.

1 comments

That's not quite random, because you're selecting items with probability 1/RAND_MAX. The elements beyond RAND_MAX will never be selected.