Give you:
next()
to get the next element in the stream and advance the pointer in the streamOutput:
You can one or two variables.
You are not allowed to use array / list, and you cannot tell the way that trying to get all elements out and store them all and then pick
.
This is an interview question.
My thinking is:
cur
to store most recent kept elementcur = new element
; otherwise, continue;Is my thinking correct? How to prove?
Here is a same question
How would you pick a uniform random element in linked list with unknown length?
Let the current element's index be i
.
Choose to 'remember' the current element at probability 1/i
. When EOF is reached, produced the element you remember.
At the end, for each element with index i
there is a probability to be chosen:
A formal prove can be done using induction, following these guidelines.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With