Two Buttons Problem
Two Buttons Problem — ExecCode Medium DSA Practice
Solve the Two Buttons problem on ExecCode. Free online medium DSA practice in Graph. Write and run code in Java, C++, Python — no signup required to run.
Problem description
An integer starts at n. One button multiplies the current integer by 2. The other button subtracts 1. The integer must stay positive. Return the minimum number of button presses that turns n into m. You are given: n — the starting integer m — the target integer Return the minimum number of presses. If the target is smaller, the only useful button is subtract. Otherwise search the doubles and decrements, or walk backward from the target by halving even numbers and adding 1 to odd numbers.
Examples
Input {'n': 4, 'm': 6}; Output 2. Input {'n': 10, 'm': 1}; Output 9. Input {'n': 1, 'm': 1}; Output 0
Constraints
1 <= n, m <= 10000
Practice Two Buttons free on ExecCode. Browse DSA problems, topic map, and placement guides.