Convert a number m to n with minimum operations. The operations allowed were subtraction by 1 and multiplication by 2.
For Eg : 4 and 6. Answer is 2. 1st operation : -1
Your algorithm is exponential, at each additional "breadth level" you add 2 new values for each value in the previous level. For example:
26 (breadth = 0)
25, 52 (breadth = 1)
24, 50, 51, 104 (breadth = 2)
23, 48, 49, 100, 50 (skipped because seen), 102, 103, 208 (breadth = 3)
22, 46, 47, 96, 48 (skip), 98, 99, 200 (breadth = 4)
21, 44, 45, 92, 46, 94, 95, 192, 97, 196, 199, 400 (breadth = 5)
The solution for the case src=26, dst=5 is to subtract 1 until you reach 5, that takes 21 "breadth levels" = 21 operations. At that level both your queue and your seen_list
will contain ~2^20 values; and for each value in the queue you do a linear search to see if it's present in the list, so that level will consist of 2^20 * 2^20 comparisons = 2^40 ~ 1 thousand billion comparisons. That takes time, and it's just the last level.
You should think of a better algorithm. For starters, if your current value is higher than the target, there is no point in doubling it as it will surely only add additional steps..
This consideration alone will reduce the number of steps for this case from millions to 21 (you'll just subtract 1 until you reach the target value, and this will happen in general when src > dest
)