#1 it depends how do you define efficient
Do your heap needs to occupy O(N) memory with the 2 * nod + 1 trick for sons, or it should be just a tree with heap property
#2 keep a heap with the first element of every array.
take the smallers one from that heap and put the next element from that array into the heap
O(sum_or_arrays * logK)
#3 keep a min-heap with the first k elements in it. Erase the top, put it in #1 and put #k+1 into the heap -> repeat O(NlogK)
#4 -> you can keep a max-heap limited to size k
insert into heep. while(heap.size() > k) { heap.pop(); }
O(N + NlogK)
ORRRRR you can use kTh element and then sort the first k elements of the array.
it depends if the first K elements should be sorted or not O(N) vs O(N + KlogK)
#5 > or >= ?
#6 I won't fall for that problem AGAIN
someone told me like 3 years ago. From what I heard it was given to Bogdan Tataroiu at his Google/Dropbox interview(I don't remember). And there is the O(KlogK) solution, but there is another O(K) solution. I thought about if for 2 years, and then someone told me it's a cool paper and stuff ..
But there is O(K)
#7 immagine that you have the first 8 numbers computed
Than we want to expand this sequence further, and if we want to expand it with 2, the next element whould be at least [12 / 2] + 1
in this case, 8, since we can't make 7
The same applies for 3, [12 / 3] + 1 = 5 -> 6
now we just take the smallest of these numbers and go on.
We don't have to binary search this positions, since they will only grow.
We can just keep 2 pointers at every moment and just itterate throu them.
-> O(N) and prints first N elements made out of 2 and 3
Here is some python code for it
#n = int(raw_input())
n = 5000000
exp = [2, 3]
where = [0, 0]
rez = [1]
now = [0, 0]
for i in range(n - 1):
for i in range(2):
now[i] = exp[i] * rez[where[i]]
mn = min(now)
rez.append(mn)
for i in range(2):
if now[i] == mn:
where[i] += 1
print rez
OFFTOPIC
if you just want the Nthelement, or the sum of the first N elements for 2 factors you can get that in
O(sqrt(N)*logN)
I made a test for factors 2, 3 and 5 and the algo runs in O(N^(2/3) * logN)
and that is a big improvement, since the memory is O(1)
Here is some C++ code for factors (2, 3, 5) and it runs is 0.4 for 10^8 -> BEAT THAT O(N)
http://ideone.com/wwn5QDI really like this problem
#8
We have
maxHeap - minHeap
if we have 2*n elements
we keep the lower N elements in maxHeap, than the biggest N elements in the minHeap
if the 2 heaps are equal, the medial is maxHeap.top()
else, it is the.top() of the biggest Heap.
Now we want to keep the abs(maxHeap.size() - minHeap.size()) <= 1
if that overflows, we just.pop one and push the value in the other heap.
#9 problem #9 and #5 are mostly the same, since in #9 C
[j] = A + B[j] and C is a Young Tableau
#10
The solution should be better than O(K), right?