In the expression
2x * 3y * 5z
The x
, y
and z
can take non negative integer value (>=0).
So the function would generate a series of number 1,2,3,4,5,6,8,9,10,12,15,16....
What I would like to have is an elegant algorithm.
This is an interview question.
This can be solved using a priority queue, where you store triplets (x, y, z) sorted by the key 2x3y5z.
Start with only the triplet (0, 0, 0) in the queue.
Remove the triplet (x, y, z) with the smallest key from the queue.
Insert the three triplets (x+1, y, z), (x, y+1, z) and (x, y, z+1) in the queue. Make sure you don't insert anything that was already there.
Repeat from step 2 until you've removed k triplets. The last one removed is your answer.
In effect, this becomes a sorted traversal of this directed acyclic graph. (First three levels shown here, the actual graph is of course infinite).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With