VOOZH about

URL: https://www.geeksforgeeks.org/dsa/reduce-n-to-1-by-given-operations/

⇱ Reduce N to 1 by given operations - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Reduce N to 1 by given operations

Last Updated : 23 Jul, 2025

Given an integer N. Then your task is to output a minimum number of operations to reduce N into 1. You can below operations to do the same:

  • Subtract 1 from N
  • Update N to N/2, if N is divisible by 2
  • Update N to N/3, if N is divisible by 3

Examples:

Input: N = 10
Output: 3
Explanation: The operations are performed as:

  • First Operation: Subtract 1 form 10. Updated value of N = 9.
  • Second Operation: N = 9 is divisible by 3. Update N as 9/3 = 3
  • Second Operation: N = 3 is divisible by 3. Update N as 3/3 = 1

Now N is reduced into 1 by following sequence of N's value as {10 → 9 → 3 → 1}. Thus, minimum number of operations required are 3.

Input: 4
Output: 2
Explanation: 4 can be reduced into 1 with two ways {4 → 3 → 1} or {4 → 2 → 1}. Both requires minimum operations as 2.

Approach: Implement the idea below to solve the problem

In this problem we have 3 choices to perform operations, in solving choice-based problems we can use Dynamic Programming. For this problem we will take help of Dynamic Programming in the form of map and for each value of N, we can explore all the given conditions and can proceed further with minimum of them.

Steps were taken to solve the problem:

  • Initialize a map let say DP.
  • Definition of recursive function ReduceTo1(N):
    • If (N <= 1)
      • Return 0
    • If (map DP contains N)
      • Return DP[N]
    • Create a variable let say Min_op to store minimum number of operations and initialize it equal to (1+min(N % 2 + ReduceTo1(N / 2), N % 3 + ReduceTo1(N / 3)))
    • DP[N] = Min_op
    • Return Min_op

Below is the code to implement the above approach:


Output
3

Time Complexity: O(Log N)
Auxiliary Space: O(Log N)

Comment