Fewest increment or double moves to reach a target from 1

Quick Overview

Starting from a score of 1, each move adds 1 to the score or doubles it, and the task is to find the fewest moves that land exactly on a target of up to one billion. It tests reasoning backward from the goal, proving a greedy choice optimal, and keeping the work logarithmic.

Fewest increment or double moves to reach a target from 1

Role: Software Engineer

Category: Coding & Algorithms

Difficulty: easy

Interview Round: Other

You start with a score of `1`. In one move you may either increment your current score by `1` or double it. Given an integer `target`, return the minimum number of moves required to reach exactly `target`. ### Function Signature ```python def min_moves(target: int) -> int: ``` ### Rules - A move replaces the current score `s` with `s + 1` or with `2 * s`. - The score never decreases, so a path that passes `target` cannot come back to it. - When `target` is `1` the score already matches, and the answer is `0`. ### Constraints - `1 <= target <= 10^9` ### Examples ```text Input: target = 10 Output: 4 ``` One optimal path is `1 -> 2 -> 4 -> 5 -> 10`. After three moves the score can only be 4, 5, 6 or 8, so no shorter path exists. ```text Input: target = 1 Output: 0 ``` The starting score already equals the target, so no moves are needed. ```text Input: target = 7 Output: 4 ``` One optimal path is `1 -> 2 -> 3 -> 6 -> 7`. Seven is odd, so the last move has to be an increment from 6, and reaching 6 takes three moves of its own.

Overview: Starting from a score of 1, each move adds 1 to the score or doubles it, and the task is to find the fewest moves that land exactly on a target of up to one billion. It tests reasoning backward from the goal, proving a greedy choice optimal, and keeping the work logarithmic.

Nov 24, 2026
easySoftware EngineerOtherCoding & Algorithms
0
0

You start with a score of 1. In one move you may either increment your current score by 1 or double it.

Given an integer target, return the minimum number of moves required to reach exactly target.

Function Signature

def min_moves(target: int) -> int:

Rules

  • A move replaces the current score s with s + 1 or with 2 * s .
  • The score never decreases, so a path that passes target cannot come back to it.
  • When target is 1 the score already matches, and the answer is 0 .

Constraints

  • 1 <= target <= 10^9

Examples

Input: target = 10
Output: 4

One optimal path is 1 -> 2 -> 4 -> 5 -> 10. After three moves the score can only be 4, 5, 6 or 8, so no shorter path exists.

Input: target = 1
Output: 0

The starting score already equals the target, so no moves are needed.

Input: target = 7
Output: 4

One optimal path is 1 -> 2 -> 3 -> 6 -> 7. Seven is odd, so the last move has to be an increment from 6, and reaching 6 takes three moves of its own.