number theory
algorithms
mathematical optimization
problem solving
integer reduction

minimum number of steps to reduce number to 1

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

In the world of computer science, numerous problems revolve around manipulating numbers through various operations to achieve a specific objective. One such intriguing problem is determining the minimum number of steps required to reduce a number to 1 through a set of defined operations. This problem is often encountered in algorithm challenges and can be approached using dynamic programming or greedy strategies.

Problem Statement

The objective is to reduce a given integer, `n`, to 1 by performing any of the following operations the least number of times:

  1. If `n` is divisible by 3, divide it by 3.
  2. If `n` is divisible by 2, divide it by 2.
  3. Subtract 1 from `n`.

Example

To clearly understand the problem, let's take an example where `n = 10`.

  • 10910 \rightarrow 9 (Subtract 1)
  • 939 \rightarrow 3 (Divide by 3)
  • 313 \rightarrow 1 (Divide by 3)

In this example, we achieve the result in 3 steps.

Approach Using Dynamic Programming

Dynamic programming (DP) provides an efficient solution to this problem by breaking it down into simpler subproblems, storing the results of subproblems to avoid redundant computations.

Step-by-Step DP Solution

  1. Define the State: Let `dp[i]` represent the minimum number of steps needed to reduce `i` to 1.
  2. Initialization: Initialize `dp[1] = 0` because no steps are needed to reduce 1 to 1.
  3. Recurrence Relation: For each i (from 2 to n), compute:
    • If `i` is divisible by 3: `dp[i] = 1 + dp[i/3]`
    • If `i` is divisible by 2: `dp[i] = 1 + dp[i/2]`
    • Otherwise: `dp[i] = 1 + dp[i-1]` Choose the minimum among the possible operations.
  4. Compute and Return the Result: Implement the loop for `i` from 2 to `n` and at the end, `dp[n]` contains the minimum number of steps required to reduce `n` to 1.

Complexity

  • Time Complexity: O(n)O(n) because we are solving each subproblem (for each `i` from 2 to `n`) exactly once.
  • Space Complexity: O(n)O(n) for storing the array `dp`.

Example Code Implementation (Python)


Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

All Rights Reserved.