Skip to content

Latest commit

 

History

History
5 lines (4 loc) · 1.58 KB

File metadata and controls

5 lines (4 loc) · 1.58 KB

Two Buttons Editorial

The basic idea of this problem is that we can recurse through each possible button press (which gets us closer to m) to get a solution. Of course, if we aimlessly press buttons, then we could easily get a sequence that is infinite and we'll definetly get stack overflow. Therefore, we have to set some rules: if n > m, then use the -1 operation, and if n < m, then use the *2 operation. This typically works, but here we run into a problem. Consider a case such as '5 8': here, our program would multiply by two, and then substract one twice, which is the path that immediately comes to mind. Unfortunately, a faster path would be to substract by one and multiply by two (which is two presses compared to three, so it's the most efficient). To solve this, we can use a little trick: instead of going from n to m, we can go backwards, also known as m to n. This would solve all the cases the n to m attempt could solve, as well as being able to solve the '5 8' case. The only slight issue is that not all numbers are divisibly by two (remember, we need to reverse the operation since we are going backwards to forwards, so *2 becomes /2 and -1 becomes +1), so we just need to add a check if the number is divisible by two (if not do -1), and we have our solution!

Time Complexity

Since the only real time-consuming part is the recursion, let's go with just that. At each step, we do a short calculation, then make one of two choices. Imagining the time would be highest when we have to do all +1s (specifically when n = 1 and m = 10000), the worst time complexity would be O(m - n).