Open In App

Smallest number greater than K by removing digits from N

Last Updated : 12 May, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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

Output
1120

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));

Output
1120

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.


Next Article

Similar Reads