Microsoft Interview Question
Software Engineer / DevelopersCountry: United States
Interview Type: In-Person
Construction of min heap of size n for the given input series and then clearing the min heap will give us the required result. Complexity is O(n log n).
Adding element to min heap is O(log n) as it requires correction of the heap through log levels. For n elements it would be O(n log n).
int *findLowestUniqueNumber(int a[], int n){
int m = sizeof(a)/sizeof(int);
int *res = malloc(sizeof(int)*n);
int *temp = malloc(sizeof(int)*m);
memset(res, 0, sizeof(int)*n);
memset(temp, 0, sizeof(int)*m);
int min = 0;
for (int i = 0; i < n; i++){
int minFlag = 0 ;
min = a[0];
for (int j = 0; j < m; j++){
if (temp[j] == 0){
if (min >= a[j]){
min = a[j];
temp[j] = min;
minFlag = 1;
}
}
}
if (minFlag == 0){
temp[0] = min;
}
}
int k = 0;
// remove 0s
for (int i = 0; i < m; i++){
if (temp[i] != 0){
res[k++] = temp[i];
}
}
free(temp);
return res;
}
def min_heapify(a,i):
l = 2*i+1
r = 2*i+2
min = i
if (l < len(a) and a[l] < a[i]):
min = l
if (r < len(a) and a[r] < a[min]):
min=r
if (min != i):
a[i],a[min] = a[min],a[i]
min_heapify(a,min)
if __name__ == '__main__':
temp = [5,3,17,10,84,19,6,22,9]
print ('enter the number:')
n = int(input())
for i in range(n):
for j in range (int(math.ceil(len(temp)/2)),-1,-1):
min_heapify(temp,j)
print (temp[0])
temp = temp[1:]
Could someone elaborate the question. The way i understand it we have a stream of numbers and we have to return all numbers less than a given number (n). And that seems to be a trivial problem.
There are two efficient solutions.
1) Create a bst (allow duplicates)out of these numbers. Each time a query comes, it would take O(k) time to get k least numbers. Here the catch is insertion time O(logn)
2) Store all these numbers in an array. Apply selection algorithm each time a query comes. Here it will take O(n) time to figure out the least k numbers. Also there is a huge constant factor involved in this method. Insertion takes O(1). If array size needs to be increased, that will take O(n) time. Also deletion is a problem here.
selection algorithm, find max or min k numbers.
- samuel February 24, 2014