Amazon Interview Question
Software Engineer / Developersrun partial quicksort. at each level check if m is less than the no of elements on the left partion. if so execute quick sort on the left else on the right with m = m - no of elements on right. if final pivot index == m return value in m. This is linear on an average case.
This is nothing but a Selection algorithm. This solution seems to be the best, considering no extra array space or heap space.
But the question says "without sorting".
How about making a bin search tree out of elements and then searching it?
how about a binary min-heap(BMH), similar to ~amv's suggestion.
But no need to heapify the whole array of m elements.
Only keep the n largest sorted.
FOR (list[i=0...m]) { # O(m)
IF ( i <= n )
THEN
insertToBMH(list[i], BMH) # O(log n)
ELSE
min = minValue(BMH) # O(1), just get the root
IF ( list[i] > min )
swap(list[i], BMH-root) # O(1)
heapfiyDown(BMH) # O(log n), bubble-down list[i] from root
END-IF
END-IF
END-FOR
nth-largest = getRoot(BMH) # O(1)
Overall, O(m * 2 * log n)) = O(m log n)
in array if space complexity doesnt matter the u can do it by making the binarey seach tree of n numbers and finding the kth largest number by just doint the Inorder Traversal :)
but if it also mattrers and u can not rearrange the array it is sure to have that solution will take O(n2) at worse case
if it is right to rearrange the order of elemnts then u can only able tio solve this problem in O(n) solution :)
this is a C++ concept - that states point to member - n->0 translates to n to member functions(m).
- Anonymous February 27, 2010use a selection algorthm with :
function select(list[1..n], k)
for i from 1 to k
minIndex = i
minValue = list[i]
for j from i+1 to n
if list[j] < minValue
minIndex = j
minValue = list[j]
swap list[i] and list[minIndex]
return list[k]