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.
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:
- If `n` is divisible by 3, divide it by 3.
- If `n` is divisible by 2, divide it by 2.
- Subtract 1 from `n`.
Example
To clearly understand the problem, let's take an example where `n = 10`.
- (Subtract 1)
- (Divide by 3)
- (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
- Define the State: Let `dp[i]` represent the minimum number of steps needed to reduce `i` to 1.
- Initialization: Initialize `dp[1] = 0` because no steps are needed to reduce 1 to 1.
- 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.
- 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: because we are solving each subproblem (for each `i` from 2 to `n`) exactly once.
- Space Complexity: for storing the array `dp`.
Example Code Implementation (Python)
Related reading
- Minimum number of swaps needed to change Array 1 to Array 2?
- Minimum number of swaps to convert a string into another string
- Minimum number of swaps to convert a string to palindrome
- Minimum number X such that X P N
- Minimum number of train station stops
- Minimum rectangles required to cover a given rectangular area
- Modulo of Division of Two Numbers
- Modulo of negative numbers

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 courseTrack 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.