VOOZH about

URL: https://www.geeksforgeeks.org/dsa/minimize-operations-to-convert-n-to-a-power-of-k-by-removing-or-appending-any-digit/

⇱ Minimize operations to convert N to a power of K by removing or appending any digit - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Minimize operations to convert N to a power of K by removing or appending any digit

Last Updated : 23 Jul, 2025

Given a number N, the task is to find the minimum number of operations to convert the given integer into any power of K where at each operation either any of the digits can be deleted or any of the digits can be appended at the back of the integer.

Examples:

Input: N = 247, K = 3
Output: 1
Explanation: In the 1st operation, digit 4 can be removed. Hence, N = 27 which is a power of K.

Input: N = 5, K = 2
Output: 2
Explanation: In the 1st operation, digit 5 can be removed and in the 2nd operation, digit 2 can be appended in the end. Hence, N = 2 which is a power of K.

Approach: The given problem can be solved by storing all the powers of K in a vector and calculating the number of operations required to convert the given integer N into the current power. Below are the steps to follow: 

  • Store all powers of K in vector powers.
  • Now traverse through the vector powers and calculate the number of operations required to convert the given integer N into the current power which can be done as follows:
    • Convert the given integers into strings s1 and s2.
    • Initialize two variables i = 0 and j = 0.
    • If  s1[i] is equal to s2[j], increment both i and j. Otherwise, increment j only.
    • The required number of operations will be S1.length + S2.length - (2 * i).
  • Maintain the minimum of the required operations over all values which is the required answer.

Below is the implementation of the above approach:

 
 


Output
1


 

Time Complexity: O((log N)2)
Auxiliary Space: O(1)


 

Comment