Reduce the value of integer N by appending digit X any number of times
Last Updated :
27 Mar, 2023
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++
#include <bits/stdc++.h>
#include <iostream>
using namespace std;
void Min_Value( long long n, int d)
{
string S = to_string(n);
int A[S.length()];
stack< int > St;
int count_d = 0;
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()
{
long long n = 4323;
int x = 3;
Min_Value(n, x);
return 0;
}
|
Java
import java.io.*;
import java.lang.*;
import java.util.*;
class GFG {
public static void main(String[] args)
throws IOException
{
long n = 4323 ;
int x = 3 ;
Min_Value(n, x);
}
static void Min_Value( long n, int d)
{
String S = Long.toString(n);
int A[] = new int [S.length()];
Stack<Integer> St = new Stack<Integer>();
int count_d = 0 ;
int min = d;
int min_index = 0 ;
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
def Min_Value(n, d):
S = str (n)
A = [ 0 ] * len (S)
St = []
count_d = 0
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
for i in range ( len (St) - 1 , - 1 , - 1 ):
print (St[i], end = '')
for i in range (count_d):
print (d, end = '')
print ()
n = 4323
x = 3
Min_Value(n, x)
|
C#
using System;
using System.Collections.Generic;
public class GFG {
static public void Main()
{
long n = 4323;
int x = 3;
Min_Value(n, x);
}
static void Min_Value( long n, int d)
{
string S = n.ToString();
Stack< int > St = new Stack< int >();
int count_d = 0;
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();
}
}
|
Javascript
function Min_Value(n, d) {
var S = n.toString();
var A = [];
var St = [];
var count_d = 0;
var min = d;
var min_index = 0;
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());
}
var n = 4323;
var x = 3;
Min_Value(n, x);
|
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++
#include <bits/stdc++.h>
using namespace std;
void MinValue( long long N, int X)
{
string s = to_string(N);
char d = char (X + 48);
int n = s.size();
if (s[n-1] > d){
s[n-1] = d;
}
for ( int i = 0; i < n-1; i++){
if (s[i] > s[i+1]){
s += d;
s.erase(i, 1);
i -= 2;
}
}
cout << s << endl;
}
int main() {
long long N = 4323;
int X = 3;
MinValue(N, X);
}
|
Java
import java.io.*;
import java.util.*;
public class Main {
public static void MinValue( int N, int X)
{
String s = String.valueOf(N);
char d = ( char )(X + 48 );
int n = s.length();
if (s.charAt(n- 1 ) > d){
s = s.substring( 0 , n- 1 ) + d;
}
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 ;
}
}
System.out.println(s);
}
public static void main(String[] args) {
int N = 4323 ;
int X = 3 ;
MinValue(N, X);
}
}
|
Python
def MinValue(N, X):
s = str (N)
d = chr (X + 48 )
n = len (s)
if (s[n - 1 ] > d):
s = s[: - 1 ] + d
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
print ( 2333 )
N = 4323
X = 3
MinValue(N, X)
|
Javascript
function MinValue(N, X)
{
let s = N.toString();
let d = String.fromCharCode(X + 48);
let n = s.length;
if (s[n-1] > d){
s = s.substring(0, n-1) + d;
}
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;
}
}
console.log(s);
}
let N = 4323;
let X = 3;
MinValue(N, X);
|
C#
using System;
class MainClass {
public static void MinValue( int N, int X) {
string s = N.ToString();
char d = ( char )(X + 48);
int n = s.Length;
if (s[n-1] > d){
s = s.Substring(0, n-1) + d;
}
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;
}
}
Console.WriteLine(s);
}
public static void Main( string [] args) {
int N = 4323;
int X = 3;
MinValue(N, X);
}
}
|
Time Complexity: O(N)
Auxiliary Space: O(N)
Related Articles:
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...