KatInterview

Fewest Steps to Reach One

Math & Bit ManipulationAuto-graded · 27 test cases
MediumAuto-gradedMath & Bit Manipulationgreedybit-manipulationmath

Last updated

Tests greedy reasoning over binary structure to find the minimum number of halving and increment/decrement steps needed to reduce a positive integer to 1.

Problem

You have a positive integer num. Each step, you may apply exactly one of the following rules:

  • If num is even, replace it with num // 2.
  • If num is odd, replace it with either num + 1 or num - 1.

Return the fewest steps needed to bring num down to exactly 1.

Rules and Tie-breaking

When num is even, halving is the only available rule, so no decision is needed.

When num is odd, you must pick between adding and subtracting. The right choice depends on the two lowest bits of num:

  • If the last two bits are 01 (i.e., num % 4 == 1), subtract 1.
  • If the last two bits are 11 (i.e., num % 4 == 3) and num > 3, add 1.
  • The value num = 3 is a special case: subtract 1 (giving 2 → 1) rather than adding (giving 4 → 2 → 1), because the target is already one step away via the shorter path.

Constraints

  • 1 <= num <= 2^31 - 1
  • num is a positive integer.

Examples

Example 1

Input: fewest_steps_to_one(8)

Output: 3

Example 2

Input: fewest_steps_to_one(7)

Output: 4

Example 3

Input: fewest_steps_to_one(1)

Output: 0

Example 4

Input: fewest_steps_to_one(3)

Output: 2

Hints

Hint 1

When num is even you have no choice at all — think about where the real decisions happen and focus your energy there.

Hint 2

Look two bits ahead instead of one: does the number end in ...01 or ...11 in binary? One pattern favors subtracting, the other favors adding — figure out which and why.

Hint 3

Check what happens at num = 3 specifically: plugging into the general rule gives the wrong answer, so handle it as an explicit special case before applying the mod-4 logic.