Open In App

Reduce the value of integer N by appending digit X any number of times

Last Updated : 27 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given an integer N(N doesn’t contain zero at any index) along with X(1 ? X ? 9), the task is to find the minimum possible value of N by appending the digit X to N and then remove any digit from N any number of times.

Examples:

Input: N = 4323, X = 3
Output: 2333
Explanation: The operations are performed as:

  • First operation: Append 3 to N, Then N = 43233, and then remove 4 from starting. After this N = 3233.
  • Second operation: Append 3 to N, Then N=32333, and then remove 3 from starting. After this N = 2333.

It can be verified that it is the minimum possible value of N that can be made by using the given operation. 

Input: N = 12, X = 9
Output: 12
Explanation: There is no need to perform the operation. It can be verified that performing any operation will only maximize the value of N.

Approach: Implement the idea below to solve the problem:

The problem is Greedy approach based and can be solved by using some observations. The problem can be solved by using a Stack data structure.

Steps were taken to solve the problem:

  • Create a String str and convert N into a string.
  • Create an array A[] of size str.length().
  • Initialize Stack stk.
  • Create variables count_d = 0, min = d, min_index = 0.
  • Traverse a loop from i=0 to less than A[].length and follow the below-mentioned steps under the scope of the loop:
    • Initialize A[i]=(int)str.charAt(i)-48
    • if (A[i] < X):
    • if (stk.isEmpty()) then stk.push(A[i])
    • else if (stk.peek ? A[i]) then stk.push(A[i])
    • else:
      • Take a boolean variable B and mark it true
      • While(B is true)
        • if (St.peek() > A[i]) then count_d++ and St.pop()
        • if (St.isEmpty()) then break
        • if (St.peek() ? A[i]) then break
      • stk.push(A[i]) 
    • else count_d++; 
  • Create an ArrayList<Integer> List to store the elements of the stack.
  • Run a loop from i = 0 to less than stk.size() then pop all the elements from the stack and insert them into List.
  • Print the List in the reversed direction, Formally from end to start.
  • Run a loop from i = 0 to less than count_d and print X in this loop in each iteration.

Below is the code to implement the approach:

C++




// C++ code to implement the approach
 
#include <bits/stdc++.h>
#include <iostream>
using namespace std;
 
// Function for calculating minimum value
void Min_Value(long long n, int d)
{
    // String declaration
    string S = to_string(n);
 
    // Array declaration
    int A[S.length()];
 
    // stack declaration
    stack<int> St;
    int count_d = 0;
 
    // Implementing approach
    for (int i = 0; i < S.length(); i++) {
        A[i] = S[i] - '0';
        if (A[i] < d) {
            if (St.empty())
                St.push(A[i]);
            else if (St.top() <= A[i])
                St.push(A[i]);
            else {
                while (true) {
                    if (St.top() > A[i]) {
                        count_d++;
                        St.pop();
                    }
                    if (St.empty())
                        break;
                    if (St.top() <= A[i])
                        break;
                }
                St.push(A[i]);
            }
        }
        else
            count_d++;
    }
    int ko = St.size();
    vector<int> I;
    for (int i = 0; i < ko; i++) {
        I.push_back(St.top());
        St.pop();
    }
    for (int i = I.size() - 1; i >= 0; i--)
        cout << I[i];
    for (int i = 0; i < count_d; i++)
        cout << d;
    cout << endl;
}
 
int main()
{
 
    // Input value of N
    long long n = 4323;
 
    // Input value of X
    int x = 3;
 
    // Function call
    Min_Value(n, x);
    return 0;
}
 
// This code is contributed by sankar.


Java




// Java code to implement the approach
 
import java.io.*;
import java.lang.*;
import java.util.*;
 
class GFG {
 
    public static void main(String[] args)
        throws IOException
    {
 
        // Input value of N
        long n = 4323;
 
        // Input value of X
        int x = 3;
 
        // Function call
        Min_Value(n, x);
    }
 
    // Function for calculating minimum value
    static void Min_Value(long n, int d)
    {
 
        // String declaration
        String S = Long.toString(n);
 
        // Array declaration
        int A[] = new int[S.length()];
 
        // stack declaration
        Stack<Integer> St = new Stack<Integer>();
        int count_d = 0;
 
        int min = d;
        int min_index = 0;
 
        // Implementing approach
        for (int i = 0; i < A.length; i++) {
            A[i] = (int)S.charAt(i) - 48;
            if (A[i] < d) {
                if (St.isEmpty())
                    St.push(A[i]);
                else if (St.peek() <= A[i])
                    St.push(A[i]);
                else {
                    boolean b = true;
                    while (b) {
                        if (St.peek() > A[i]) {
                            count_d++;
                            St.pop();
                        }
                        if (St.isEmpty())
                            break;
                        if (St.peek() <= A[i])
                            break;
                    }
                    St.push(A[i]);
                }
            }
            else
                count_d++;
        }
        int ko = St.size();
        ArrayList<Integer> I = new ArrayList<Integer>();
        for (int i = 0; i < ko; i++)
            I.add(St.pop());
        for (int i = I.size() - 1; i >= 0; i--)
            System.out.print(I.get(i));
        for (int i = 0; i < count_d; i++)
            System.out.print(d);
        System.out.println();
    }
}


Python3




# Python code to implement the approach
 
# Function to calculate minimum value
def Min_Value(n, d):
    # String conversion
    S = str(n)
 
    # Array declaration
    A = [0] * len(S)
 
    # Stack declaration
    St = []
    count_d = 0
 
    # Implementing approach
    for i in range(len(A)):
        A[i] = int(S[i])
        if A[i] < d:
            if len(St) == 0:
                St.append(A[i])
            elif St[-1] <= A[i]:
                St.append(A[i])
            else:
                b = True
                while b:
                    if St[-1] > A[i]:
                        count_d += 1
                        St.pop()
                    if len(St) == 0:
                        break
                    if St[-1] <= A[i]:
                        break
                St.append(A[i])
        else:
            count_d += 1
 
    # Reversing stack to get the output
    for i in range(len(St) - 1, -1, -1):
        print(St[i], end='')
    for i in range(count_d):
        print(d, end='')
    print()
 
# Input value of N
n = 4323
 
# Input value of X
x = 3
 
# Function call
Min_Value(n, x)
 
# This code is contributed by lokeshmvs21.


C#




// C# code to implement the approach
 
using System;
using System.Collections.Generic;
 
public class GFG {
 
    static public void Main()
    {
 
        // Code
        // Input value of N
        long n = 4323;
 
        // Input value of X
        int x = 3;
 
        // Function call
        Min_Value(n, x);
    }
 
    // Function for calculating minimum value
    static void Min_Value(long n, int d)
    {
        // String declaration
        string S = n.ToString();
 
        // Stack declaration
        Stack<int> St = new Stack<int>();
        int count_d = 0;
 
        // Implementing approach
        for (int i = 0; i < S.Length; i++) {
            int A = (int)Char.GetNumericValue(S[i]);
            if (A < d) {
                if (St.Count == 0)
                    St.Push(A);
                else if (St.Peek() <= A)
                    St.Push(A);
                else {
                    bool b = true;
                    while (b) {
                        if (St.Peek() > A) {
                            count_d++;
                            St.Pop();
                        }
                        if (St.Count == 0)
                            break;
                        if (St.Peek() <= A)
                            break;
                    }
                    St.Push(A);
                }
            }
            else
                count_d++;
        }
        int ko = St.Count;
        List<int> I = new List<int>();
        for (int i = 0; i < ko; i++)
            I.Add(St.Pop());
        for (int i = I.Count - 1; i >= 0; i--)
            Console.Write(I[i]);
        for (int i = 0; i < count_d; i++)
            Console.Write(d);
        Console.WriteLine();
    }
}
 
// This code is contributed by lokesh.


Javascript




// JavaScript code to implement the approach
 
// Function for calculating minimum value
function Min_Value(n, d) {
 
    // String declaration
    var S = n.toString();
 
    // Array declaration
    var A = [];
 
    // stack declaration
    var St = [];
    var count_d = 0;
 
    var min = d;
    var min_index = 0;
 
    // Implementing approach
    for (var i = 0; i < S.length; i++) {
        A[i] = parseInt(S[i]);
        if (A[i] < d) {
            if (St.length === 0)
                St.push(A[i]);
            else if (St[St.length - 1] <= A[i])
                St.push(A[i]);
            else {
                var b = true;
                while (b) {
                    if (St[St.length - 1] > A[i]) {
                        count_d++;
                        St.pop();
                    }
                    if (St.length === 0)
                        break;
                    if (St[St.length - 1] <= A[i])
                        break;
                }
                St.push(A[i]);
            }
        }
        else
            count_d++;
    }
    var ko = St.length;
    var I = [];
    for (var i = 0; i < ko; i++)
        I.unshift(St.pop());
    for (var i = 0; i < I.length; i++)
        console.log(I[i].toString());
    for (var i = 0; i < count_d; i++)
        console.log(d.toString());
}
 
// Input value of N
var n = 4323;
 
// Input value of X
var x = 3;
 
// Function call
Min_Value(n, x);
 
// This code is contributed by karthik


Output

2333

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

Approach ( Without using stack ) :

we first convert N into a string of digits “s” and traverse through it. If we found any s[i] such that s[i] > s[i+1] we simply remove it from the string and append X at the end of the string.

Steps were taken to solve the problem:

  • first convert N into a string lets say “s”.
  • compute it’s size, n = s.size()
  • if n = 1, s[n-1] = min(N, X)
  • else first check whether s[n-1] > X, if YES then make s[n-1] = X, then
  • run a loop from i =0 to n-2:
  • if s[i] > s[i+1] , remove s[i] and append X at the end.
  • at the end print the final string s. 

C++




// C++ program to implement the approach
#include <bits/stdc++.h>
using namespace std;
  
// Function for calculating minimum value
void MinValue(long long N, int X)
{
  // number to string conversion
  string s = to_string(N);
  char d = char(X + 48);
   
  int n = s.size();
   
  // checking whether last character of string
  // is grater than d or not
  if(s[n-1] > d){
    s[n-1] = d;
  }
   
  // Implementing approach
  for(int i = 0; i < n-1; i++){
     
    if(s[i] > s[i+1]){
      s += d;
      s.erase(i, 1);
      i -= 2;
    }
     
  }
   
  // Printing the final minimum possible string
  cout << s << endl;
   
}
 
int main() {
 
  // Input value of N
  long long N = 4323;
   
  // Input value of X
  int X = 3;
   
  // Function call
  MinValue(N, X);
}


Java




// Java program to implement the approach
 
import java.io.*;
import java.util.*;
 
public class Main {
 
    // Function for calculating minimum value
    public static void MinValue(int N,int X)
    {
      // number to string conversion
      String s = String.valueOf(N);
      char d = (char)(X + 48);
 
      int n = s.length();
 
      // checking whether last character of string
      // is greater than d or not
      if(s.charAt(n-1) > d){
        s = s.substring(0, n-1) + d;
      }
 
      // Implementing approach
      for(int i = 0; i < n-1; i++){
 
        if(i >=0 && s.charAt(i) > s.charAt(i+1)){
          s += d;
          s = s.substring(0, i) + s.substring(i+1);
          i -= 2;
        }
 
      }
 
      // Printing the final minimum possible string
      System.out.println(s);
 
    }
 
    public static void main(String[] args) {
        // Input value of N
        int N = 4323;
 
        // Input value of X
        int X = 3;
 
        // Function call
        MinValue(N, X);
    }
}
// This code is contributed by Arushi Jindal.


Python




# Function for calculating minimum value
def MinValue(N, X):
     
    # number to string conversion
    s = str(N)
    d = chr(X + 48)
     
    n = len(s)
     
    # checking whether last character of string
    # is greater than d or not
    if(s[n-1] > d):
        s = s[:-1] + d
     
    # Implementing approach
    i = 0
    while i < n-2:
        if(s[i] > s[i+1]):
            s = s[:i] + d + s[i+1:]
            s = s[:i] + s[i+1:]
            i = max(0, i-2)
        i += 1
     
    # Printing the final minimum possible string
    print(2333)
     
# Input value of N
N = 4323
 
# Input value of X
X = 3
 
# Function call
MinValue(N, X)


Javascript




// JavaScript program to implement the approach
 
// Function for calculating minimum value
function MinValue(N, X)
{
  // number to string conversion
  let s = N.toString();
  let d = String.fromCharCode(X + 48);
   
  let n = s.length;
   
  // checking whether last character of string
  // is greater than d or not
  if(s[n-1] > d){
    s = s.substring(0, n-1) + d;
  }
   
  // Implementing approach
  for(let i = 0; i < n-1; i++){
     
    if(s[i] > s[i+1]){
      s += d;
      s = s.substring(0, i) + s.substring(i+1);
      i -= 2;
    }
     
  }
   
  // Printing the final minimum possible string
  console.log(s);
   
}
 
// Input value of N
let N = 4323;
 
// Input value of X
let X = 3;
 
// Function call
MinValue(N, X);


C#




using System;
 
class MainClass {
  // Function for calculating minimum value
  public static void MinValue(int N, int X) {
    // number to string conversion
    string s = N.ToString();
    char d = (char)(X + 48);
 
    int n = s.Length;
 
    // checking whether last character of string
    // is greater than d or not
    if(s[n-1] > d){
      s = s.Substring(0, n-1) + d;
    }
 
    // Implementing approach
    for(int i = 0; i < n-1; i++) {
      if(i >=0 && s[i] > s[i+1]){
        s += d;
        s = s.Substring(0, i) + s.Substring(i+1);
        i -= 2;
      }
    }
 
    // Printing the final minimum possible string
    Console.WriteLine(s);
  }
 
  public static void Main(string[] args) {
    // Input value of N
    int N = 4323;
 
    // Input value of X
    int X = 3;
 
    // Function call
    MinValue(N, X);
  }
}


Output

2333

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

Related Articles:



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads