I couldn\'t solve a question can you please help?
For i=1 to i=n/2, if A[i]<=A[2i] and A[i]<=A[2i+1] A is called as a \"bst\"
What\
I can be done in O(klogk)
, and assuming k<
The idea is to maintain a min-heap, start from the head (id==0), which is the lowest element, and iteratively add all "new candidates" (which are for a given current lowest i
- the "candidates" are 2i
and 2i+1
).
Create a new empty min-heap, where each element contains a tupple (x,i) - x is the key in the array, and i is its index
set i = 0, currIdx = 0
heap.add((i,0))
while currIdx < k:
currIdx = currIdx + 1
(x,i) = heap.popLowest()
if i != 2i: //for i=2i=0, don't add it twice:
heap.add((arr[2i],2i))
heap.add((arr[2i+1],2i+1))
return heap.getTop()
Time complexity is O(klogk)
, each operation on the heap takes O(logN)
(where N
is its current size), and the heap grows to maximal size of N=k
, so all operations on the heap is log(1) + log(2) + ... + log(k) = log((k)!)
, which is in O(klogk)
.