Broken Calculator
Updated
Problem statement
A calculator shows the number n. Only two of its keys still work:
- Minus one subtracts 1 from the number on the screen.
- Double multiplies the number on the screen by 2.
Return the fewest key presses that make the screen show m. If n already equals m, the answer is 0.
The screen can show any whole number, so a number larger than m on the way is fine.
Function
minKeyPresses(n: int, m: int) → intExamples
Example 1
n = 3m = 10return = 3Press double, minus one, double: 3 → 6 → 5 → 10. That is 3 presses. Doubling twice first (3 → 6 → 12) and then pressing minus one twice also reaches 10, but uses 4 presses. No sequence of 2 presses works, so the answer is 3.
Example 2
n = 7m = 4return = 3The start is already larger than the target. Doubling only makes the number bigger, so press minus one 3 times: 7 → 6 → 5 → 4. The answer is 3.
Example 3
n = 5m = 17return = 4One best sequence is 5 → 10 → 9 → 18 → 17 (double, minus one, double, minus one). It goes above 17 on the way. The answer is 4.
Constraints
1 <= n, m <= 10^4
More Nutanix Online Assessment questions
- Good SubsequencesOA · Seen Jul 2026
- Min Cost to Connect All PointsOA · Seen Jun 2026
- Digit Changes for a Multiple of 9OA · Seen Aug 2025
- Gas Station Loop StartOA · Seen Aug 2025
- Number of Players (for MTS2)OA · Seen Oct 2024
- Work Schedules (for MTS2)OA · Seen Oct 2024
- Minimum Operations to Convert ArrayOA · Seen Apr 2024
- No Adjacent CharactersOA · Seen Apr 2024
- Build a BST From a ListOA · Seen Nov 2022
- Delete Even-Valued Nodes From a Linked ListOA · Seen Nov 2022
Similar questions at other companies
- Minimum Rounds to Complete All TasksInfosys · OAInfosys interview questions
- Minimum-Sum Tree Fill with Unit StepsVisa · OAVisa interview questions
- Server Upgrade PlanningWells Fargo · OAWells Fargo interview questions
- Minimum N-ary Tree Depth DeletionsSnowflake · OA · PHONE SCREENSnowflake interview questions
- Task Scheduler with CooldownGoDaddy · OA
- Minimize Adjacent Squared-Difference Cost with One InsertionMcKinsey & Company · OAMcKinsey & Company interview questions
- Maximize Revenue from Decreasing InventoryChubb · OAChubb interview questions
- Minimize Adjacent Squared-Difference Cost with One InsertionMicrosoft · OAMicrosoft interview questions
- Minimum Halvings for Alternating ParityIBM · OAIBM interview questions
- Resource AllocationMaven Securities · OAMaven Securities interview questions