Amazon Interview Question
Software Engineer / DevelopersBuilding on the first reply:
Load up (1 million - 1) numbers into a heap.
Take the next number from the file:
If number is smaller than top:
Replace top with next biggest item on the heap
Insert the compared number into heap.
Time complexity = O(nlog(n)).
Naa .. IMO it works just fine to give smallest 1 million nos as the new number we are taking in just for comparison with the top most element in the max heap and memory is only used for storing data.
use selection/partition alg, basically you partition the file (like in qsort) using some pivot value and get the index of pivot value after partition. Then check if the new pivot index is equal to 1M, if it is true output the first 1M elements in file, otherwise continue to run partition in the left or right part of the file. If the pivot value is properly chosen the alg is said to be O(n)
{{
for(int left = 0, right = 1 trillion;;)
{
int pivot_index = some good pivot guess;
int new_pivot_index = partition(file, left, right, pivot_index);
if (new_pivot_index == 1M)
{
output first 1M in the file;
return;
}
if (new_pivot_index < 1M)
{
left = new_pivot_index + 1;
}
else
{
right = pivot_index - 1;
}
}
}}
formatting the code:
for(int left = 0, right = 1 trillion;;)
{
int pivot_index = some good pivot guess;
int new_pivot_index = partition(file, left, right, pivot_index);
if (new_pivot_index == 1M)
{
output first 1M in the file;
return;
}
if (new_pivot_index < 1M)
{
left = new_pivot_index + 1;
}
else
{
right = pivot_index - 1;
}
}
Implement heap with 1m number, max is on top.
- Anonymous October 20, 2010Fill it with first 1m and sort. O(M*logM), M=1m.
Then go over each number, compare to first element, if it is smaller, replace first with new one and move it to right position in heap O(logM).
Total complexity is O(NlogM).