Smallest number greater than K by removing digits from N
Last Updated :
12 May, 2024
Given two integers N and K (K<N), the task is to find the smallest number greater than K by removing digits from N.
Note: You cannot rearrange the digits of N.
Examples:
Input: N = 7182, K = 11
Output: 12
Explanation: Among all the possible combination, 12 is minimum number greater than 11.
Input: N = 121320, K = 756
Output: 1120
Explanation: Among all the possible combination, 1120 is minimum number greater than 756.
Approach: The basic idea is to
Find all the subsequences and from the possible numbers get the minimum number that is greater than K.
Follow the steps mentioned below to implement the idea:
- Initialize the 'ans' with 0.
- Take the current number and store all its digits in 'digits' array.
- Generate all possible sequences for a number.
- Maintain an integer 'mask' variable whose binary representation represents elements to be taken or elements to be removed.
- If the ith bit is 1, don't take the current element means we are removing the current element.
- If the ith bit is 0, don't take the current element.
- Now compute N from the current mask. Let's call it 'temp'. If temp > K, then ans = min(ans, temp).
- Now there are two cases for the current element for its contribution in further cases:
- Leave the current element, then mask become = mask| pow(2, i) where i represents the position of the current element.
- Include the current element, then the mask remains the same. That means the ith bit is kept 0.
- Return the ans.
Below is the implementation of the above approach.
C++
// C++ code to implement the approach
#include <bits/stdc++.h>
using namespace std;
int ans = 0;
// Function to generate all possible combination
void find(int i, vector<int>& digits, int mask, int k)
{
// Base case
if (i == digits.size())
return;
// Store the ans for current state of mask
int temp = 0;
int pow_of_10 = 1;
for (int j = digits.size() - 1; j >= 0; j--) {
int k = pow(2, j);
// If the bit is 1 means current element
// is removed in that state
if (!(mask & k)) {
temp = temp + pow_of_10 * digits[j];
pow_of_10 *= 10;
}
}
if (temp > k) {
ans = min(ans, temp);
}
int next = pow(2, i);
find(i + 1, digits, mask, k);
find(i + 1, digits, mask | next, k);
}
// Function to find number less than N greater than K
int GreaterthanK(int N, int K)
{
// Array to store digits of N
vector<int> digits;
int M = N;
while (M) {
digits.push_back(M % 10);
M /= 10;
}
reverse(digits.begin(), digits.end());
ans = N;
find(0, digits, 0, K);
return ans;
}
// Driver code
int main()
{
int N = 121230;
int K = 756;
// Function call
cout << (GreaterthanK(N, K)) << endl;
return 0;
}
Java
// Java code to implement the approach
import java.util.*;
class GFG{
static int ans = 0;
// Function to generate all possible combination
static void find(int i, ArrayList<Integer> digits , int mask, int k)
{
// Base case
if (i == digits.size())
return;
// Store the ans for current state of mask
int temp = 0;
int pow_of_10 = 1;
for (int j = digits.size() - 1; j >= 0; j--) {
int kk = (int)Math.pow(2, j);
// If the bit is 1 means current element
// is removed in that state
if ((mask & kk)==0) {
temp = temp + pow_of_10 * digits.get(j);
pow_of_10 *= 10;
}
}
if (temp > k) {
ans = Math.min(ans, temp);
}
int next = (int)Math.pow(2, i);
find(i + 1, digits, mask, k);
find(i + 1, digits, mask | next, k);
}
// Function to find number less than N greater than K
static int GreaterthanK(int N, int K)
{
// Array to store digits of N
ArrayList<Integer> digits = new ArrayList<Integer>();
int M = N;
while (M>0) {
digits.add(M % 10);
M /= 10;
}
Collections.reverse(digits);
ans = N;
find(0, digits, 0, K);
return ans;
}
// Driver code
public static void main(String[] args)
{
int N = 121230;
int K = 756;
// Function call
System.out.println(GreaterthanK(N, K));
}
}
// This code is contributed by Pushpesh Raj.
Python
# Python3 code to implement the above approach
ans = 0;
# Function to generate all possible combination
def find(i, digits, mask, k) :
global ans
# Base case
if (i == len(digits)) :
return ans;
# Store the ans for current state of mask
temp = 0;
pow_of_10 = 1;
for j in range(len(digits) - 1, -1, -1) :
kk = 2 ** j;
# If the bit is 1 means current element
# is removed in that state
if ((mask & kk) == 0) :
temp = temp + pow_of_10 * digits[j];
pow_of_10 *= 10;
if (temp > k) :
ans = min(ans, temp);
next = 2 ** i;
find(i + 1, digits, mask, k);
tmp = mask | next;
find(i + 1, digits, tmp, k);
# Function to find number less than N greater than K
def GreaterthanK(N, K) :
global ans
# Array to store digits of N
digits = [];
M = N;
while M > 0:
digits.append(M % 10);
M //= 10;
digits.reverse()
ans = N;
find(0, digits, 0, K);
return ans;
# Driver code
if __name__ == "__main__" :
N = 121230;
K = 756;
# Function call
print(GreaterthanK(N, K));
# This code is contributed by AnkThon
C#
// C# implementation
using System;
using System.Collections.Generic;
public class GFG {
public static int ans = 0;
// Function to generate all possible combination
public static void find(int i, List<int> digits,
int mask, int k)
{
// Base case
if (i == digits.Count)
return;
// Store the ans for current state of mask
int temp = 0;
int pow_of_10 = 1;
for (int j = digits.Count - 1; j >= 0; j--) {
int kk = (int)Math.Pow(2, j);
// If the bit is 1 means current element
// is removed in that state
if ((mask & kk) == 0) {
temp = temp + pow_of_10 * digits[j];
pow_of_10 *= 10;
}
}
if (temp > k) {
ans = Math.Min(ans, temp);
}
int next = (int)Math.Pow(2, i);
find(i + 1, digits, mask, k);
find(i + 1, digits, mask | next, k);
}
// Function to find number less than N greater than K
public static int GreaterthanK(int N, int K)
{
// Array to store digits of N
List<int> dig = new List<int>();
int M = N;
while (M > 0) {
int rem = M % 10;
dig.Add(rem);
M = (int)(M / 10);
}
dig.Reverse();
ans = N;
find(0, dig, 0, K);
return ans;
}
static public void Main()
{
int N = 121230;
int K = 756;
// Function call
Console.WriteLine(GreaterthanK(N, K));
}
}
// this code is contributed by ksam24000
JavaScript
// JavaScript code for the above approach
let ans = 0;
// Function to generate all possible combination
function find(i, digits, mask, k) {
// Base case
if (i == digits.length)
return;
// Store the ans for current state of mask
let temp = 0;
let pow_of_10 = 1;
for (let j = digits.length - 1; j >= 0; j--) {
let k = Math.pow(2, j);
// If the bit is 1 means current element
// is removed in that state
if (!(mask & k)) {
temp = temp + pow_of_10 * digits[j];
pow_of_10 *= 10;
}
}
if (temp > k) {
ans = Math.min(ans, temp);
}
let next = Math.pow(2, i);
find(i + 1, digits, mask, k);
find(i + 1, digits, mask | next, k);
}
// Function to find number less than N greater than K
function GreaterthanK(N, K) {
// Array to store digits of N
let digits = [];
let M = N;
while (M) {
digits.push(M % 10);
M = Math.floor(M / 10);
}
digits.reverse();
ans = N;
find(0, digits, 0, K);
return ans;
}
// Driver code
let N = 121230;
let K = 756;
// Function call
console.log(GreaterthanK(N, K) + "<br>")
// This code is contributed by Potta Lokesh
Time Complexity: O(M * 2M), where M represents the length of N.
Auxiliary Space: O(M)
Approach: Optimized Subsequence Search with Early Termination
To solve the problem more efficiently than exploring all subsequences, we employ a depth-first search (DFS) strategy with pruning. The idea is to traverse the digits of N from left to right, making recursive decisions to either include or exclude each digit, forming subsequences that represent numbers. Crucially, we terminate branches early when a subsequence already exceeds the number K and is less than any previously found valid number, ensuring we only pursue the most promising candidates. This reduces unnecessary computation compared to generating all possible subsequences.
- DFS Traversal: Perform depth-first search to construct subsequences digit by digit.
- Early Pruning: Stop exploring further once we form a number greater than K and less than any previously found valid number.
- Efficient Conversion and Comparison: Convert parts of the number on-the-fly as we build it, comparing with K dynamically to make decisions based on current partial results.
C++
#include <climits>
#include <iostream>
#include <string>
void dfs(int currentIndex, std::string currentNumber,
std::string strN, int K, long long& best);
long long findSmallestNumberGreaterThanK(long long N, int K)
{
std::string strN = std::to_string(N);
long long best = LLONG_MAX;
dfs(0, "", strN, K, best);
return (best != LLONG_MAX) ? best : -1;
}
void dfs(int currentIndex, std::string currentNumber,
std::string strN, int K, long long& best)
{
if (!currentNumber.empty()) {
long long num = std::stoll(currentNumber);
if (num > K) {
best = std::min(best, num);
}
}
if (currentIndex < strN.length()) {
dfs(currentIndex + 1,
currentNumber + strN[currentIndex], strN, K,
best);
dfs(currentIndex + 1, currentNumber, strN, K, best);
}
}
int main()
{
long long N = 121230;
int K = 756;
std::cout << findSmallestNumberGreaterThanK(N, K)
<< std::endl;
return 0;
}
Java
public class Main {
static long findSmallestNumberGreaterThanK(long N,
int K)
{
String strN = Long.toString(N);
int lenN = strN.length();
long[] best = {
Long.MAX_VALUE
}; // Use an array to represent no valid number
// found yet
// Helper function to perform depth-first search
// (DFS) currentNumber is the current partial number
// being formed currentIndex is the index in the
// string strN that we are considering This function
// updates the best number found so far by
// recursively exploring all possible combinations
// of digits to form numbers greater than K The DFS
// process is similar to backtracking but instead of
// undoing changes, we just explore both including
// and excluding the current digit in the number
// being formed to cover all possible combinations
// The base case is when currentIndex reaches lenN
// In this case, we check if the currentNumber is
// greater than K If it is, we update the best
// number found so far and terminate this branch of
// exploration Otherwise, we continue exploring both
// including and excluding the current digit This
// ensures that all possible combinations are
// explored without missing any valid numbers
// greater than K Time complexity of this approach
// is O(2^N), where N is the number of digits in N
// as we explore all possible combinations of digits
// Space complexity is O(N) for the recursive call
// stack where N is the number of digits in N as we
// recurse to a depth of N to explore all possible
// combinations of digits to form numbers greater
// than K and O(N) for the string strN used to store
// the digits of N
// Start DFS from index 0 with an empty current
// number
dfs(0, "", strN, K, best);
// If best is still Long.MAX_VALUE, it means no
// valid number was found
return (best[0] != Long.MAX_VALUE)
? best[0]
: -1; // Return -1 if no number found
}
static void dfs(int currentIndex, String currentNumber,
String strN, int K, long[] best)
{
// Convert current partial number to long if it's
// not empty
if (!currentNumber.isEmpty()) {
long num = Long.parseLong(currentNumber);
// Check if the current number is a valid
// candidate
if (num > K) {
best[0] = Math.min(best[0], num);
}
}
// Recurse further if we're not at the end of the
// string
if (currentIndex < strN.length()) {
// Include current digit in the number
dfs(currentIndex + 1,
currentNumber + strN.charAt(currentIndex),
strN, K, best);
// Exclude current digit from the number
dfs(currentIndex + 1, currentNumber, strN, K,
best);
}
}
public static void main(String[] args)
{
long N = 121230;
int K = 756;
System.out.println(
findSmallestNumberGreaterThanK(N, K));
}
}
Python
def find_smallest_number_greater_than_k(N, K):
str_n = str(N)
len_n = len(str_n)
best = float('inf') # Use inf to represent no valid number found yet
def dfs(current_index, current_number):
nonlocal best
# Convert current partial number to int if it's not empty
if current_number:
num = int(current_number)
# Check if the current number is a valid candidate
if num > K:
best = min(best, num)
return # Prune this path as we already have a valid number
# Recurse further if we're not at the end of the string
if current_index < len_n:
# Include current digit in the number
dfs(current_index + 1, current_number + str_n[current_index])
# Exclude current digit from the number
dfs(current_index + 1, current_number)
# Start DFS from index 0 with an empty current number
dfs(0, "")
# If best is still inf, it means no valid number was found
return best if best != float('inf') else -1 # Return -1 if no number found
# Example usage
N = 121230
K = 756
print(find_smallest_number_greater_than_k(N, K))
JavaScript
function findSmallestNumberGreaterThanK(N, K) {
const strN = N.toString(); // Convert number N to a string
const lenN = strN.length; // Get the length of the string
let best = Infinity; // Use Infinity to represent no valid number found yet
// Helper function to perform depth-first search (DFS)
function dfs(currentIndex, currentNumber) {
// Convert current partial number to an integer if it's not empty
if (currentNumber !== "") {
const num = parseInt(currentNumber, 10);
// Check if the current number is a valid candidate
if (num > K) {
best = Math.min(best, num);
return; // Prune this path as we already have a valid number
}
}
// Recurse further if we're not at the end of the string
if (currentIndex < lenN) {
// Include current digit in the number
dfs(currentIndex + 1, currentNumber + strN[currentIndex]);
// Exclude current digit from the number
dfs(currentIndex + 1, currentNumber);
}
}
// Start DFS from index 0 with an empty current number
dfs(0, "");
// If best is still Infinity, it means no valid number was found
return best === Infinity ? -1 : best; // Return -1 if no number found
}
// Example usage of the function
const N = 121230;
const K = 756;
console.log(findSmallestNumberGreaterThanK(N, K));
Time Complexity: O(2^M), where M is the number of digits in N. Each digit has two choices: to be included or excluded from the current sequence. However, the practical running time is often less due to early pruning.
Auxilary Space: O(M), due to the recursion depth potentially going as deep as the number of digits in N. This is used to maintain the call stack of the recursive function.
Similar Reads
Smallest number greater than or equal to N divisible by K
Given a number N and a number K, the task is to find the smallest number greater than or equal to N which is divisible by K.Examples: Input: N = 45, K = 6Output: 4848 is the smallest number greater than or equal to 45which is divisible by 6.Input: N = 11, K = 3Output: 12 Approach: Approach to solve
7 min read
Smallest odd digits number not less than N
Given a number N, the task is to find the smallest number not less than N, which has all digits odd. Examples: Input: N = 1345 Output: 13511351 is the smallest number not less than N, whose all digits are odd. Input: N = 2397 Output: 3111 3111 is the smallest number not less than N, whose all digits
15+ min read
Find next greater number with same set of digits
Given a number N as string, find the smallest number that has same set of digits as N and is greater than N. If N is the greatest possible number with its set of digits, then print "Not Possible".Examples: Input: N = "218765"Output: "251678"Explanation: The next number greater than 218765 with same
9 min read
K-th smallest element after removing some integers from natural numbers
Given an array arr[] of size 'n' and a positive integer k. Consider series of natural numbers and remove arr[0], arr[1], arr[2], ..., arr[n-1] from it. Now the task is to find k-th smallest number in the remaining set of natural numbers. If no such number exists print "-1".Examples : Input: arr[] =
4 min read
Smallest even digits number not less than N
Given a number N, we need to write a program to find the smallest number not less than N, which has all digits even. Examples: Input: N = 1345 Output: 2000Explanation: 2000 is the smallest number not less than N, whose all digits are even. Input : N = 2397Output : 2400 Explanation: 2400 is the small
15+ min read
Smallest number greater than Y with sum of digits equal to X
Given two integers X and Y, find the minimal number with the sum of digits X, which is strictly greater than Y. Examples: Input: X = 18, Y = 99 Output: 189 Explanation: 189 is the smallest number greater than 99 having sum of digits = 18. Input: X = 12, Y = 72 Output: 75 Explanation: 75 is the small
11 min read
Smallest number after n removals after k day
Given a set containing all the natural numbers till infinity. You have k days and an array arr, on each day you remove a[i]th smallest natural number from the set, the task is to tell the smallest number in the set after k days. Examples: Input: N = 5, K = 1, arr[] = {1, 2, 4, 5, 6}Output: 3 Input:
5 min read
Smallest number by rearranging digits of a given number
Find the Smallest number (Not leading Zeros) which can be obtained by rearranging the digits of a given number. Examples: Input: n = 846903Output: 304689Input: n = 55010Output: 10055Input: n = -40505Output: -55400Steps to find the smallest number. Count the frequency of each digit in the number.If i
7 min read
Smallest number with at least n digits in factorial
Given a number n. The task is to find the smallest number whose factorial contains at least n digits.Examples: Input : n = 1 Output : 0 0! = 1, hence it has 1 digit. Input : n = 2 Output : 4 4! = 24 and 3! = 6, hence 4 is the smallest number having 2 digits in its factorial Input : n = 5 Output : 8
10 min read
K-th smallest element after removing given natural numbers | Set 2
Given an array arr[] of size 'n' and a positive integer k. Consider series of natural numbers and remove arr[0], arr[1], arr[2], ..., arr[n-1] from it. Now the task is to find k-th smallest number in the remaining set of natural numbers. If no such number exists print "-1".Examples: Input: arr[] = [
5 min read