VOOZH about

URL: https://www.geeksforgeeks.org/dsa/cses-solutions-removing-digits/

⇱ CSES Solutions - Removing Digits - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

CSES Solutions - Removing Digits

Last Updated : 23 Jul, 2025

You are given an integer N. On each step, you may subtract one of the digits from the number. How many steps are required to make the number equal to 0?

Examples:

Input: N = 27
Output: 5
Explanation: 27 can be reduced to 0 in 5 steps:

  • Step 1: 27 - 7 = 20
  • Step 2: 20 - 2 = 18
  • Step 3: 18 - 8 = 10
  • Step 4: 10 - 1 = 9
  • Step 5: 9 - 9 = 0

Input: N = 17
Output: 3
Explanation: 17 can be reduced to 0 in 3 steps:

  • Step 1: 17 - 7 = 10
  • Step 2: 10 - 1 = 9
  • Step 3: 9 - 9 = 0

Approach: To solve the problem, follow the below idea:

The problem can be solved using Dynamic Programming. Maintain a dp[] array such that dp[i] stores the minimum number of steps to make i equal to 0. We can iterate i from 1 to N, and for each i, and minimize dp[i] using all the digits of i.

Let's say we have already calculated minimum number of steps for all numbers from 1 to (i - 1), and now we need to calculate minimum steps for number i. To calculate minimum number of steps for number i, we will find all the digits of i and for every digit d, dp[i] = min(dp[i], 1 + dp[i - d]). After all the iterations, dp[N] will store the final answer.

Step-by-step algorithm:

  • Maintain a dp[] array such that dp[i] stores the minimum number of steps to reduce i to 0.
  • Initialize dp[0] = 0 as it takes 0 steps to reduce 0 to 0.
  • Iterate i for all numbers from 1 to N.
    • Find all the digits d of i.
    • For each digit d, update dp[i] = min(dp[i], 1 + dp[i - d]).
  • Return the final answer as dp[N].

Below is the implementation of the algorithm:


Output
3

Time Complexity: O(N * logN), where N is the number which we need to reduce.
Auxiliary Space: O(N)

Comment
Article Tags:
Article Tags: