Microsoft Interview Question
Software Engineer / DevelopersI investigated the url that u posted. thank you, the reservoir sampling problem is the exact match and i loved the idea, so clever.
In the linked list case, complexity becomes O(k*n) -In the worst case, every new element is replaced with the last element in the reservoir- That means a linear complexity. Great..
That's correct! But you should implement something like this using the linked list instead of array as the base elements. Anyway, this won't be so hard.
0. verify if k < N, if not, exit would be a solution. :)
1. create a array of size k and copy the first k elements.
2. while(list not ended) // I don't know N but I know that the list has an end
get a random index from 0 to k - 1;
move current node index positions;
replace the array[index] with the new value from current node.
Hi... Just think u r given a doubly linklist
function::
ll=head;
for(i=0;i<k;i++)
{
cnt = rand();
cnt = cnt % k;
j=0;
while(j<cnt)
{
if(ll->next != NULL)
{
ll=ll->next;
}
else
ll=ll->prev;
}
arr[i]=ll->value;
}
Every time this function will give you a new set of random nos from linklist :)
vector<int> random(ListNode* head, int k)
{
vector<int> ans(k);
while (k-- && head) {
ans.push_back(head->val);
head = head->next;
}
int i = k, j ;
while (head) {
j = rand() % (i+1);
if (j < k)
ans[j] = head->val;
i++;
}
return ans;
}
This is the "Reservoir Sampling" problem. There is an explanation of it here:
- mattj777 at yahoo September 08, 2010code-slim-jim.blogspot.com/2010/06/reservoir-sampling.html