Given an array arr[] having N integers, the task is to find the next greater number X i.e, X >= arr[i] for each i in the range [0, N) such that the count of unique digits in X is exactly 2.
Example:
Input: arr[] = {123, 234}
Output: 131 242
Explanation: For the given array, 131 is the smallest number greater that 123 having exactly 2 unique digits. Similarly, 242 is the smallest number greater that 234 having exactly 2 unique digits.Input: arr[] = {35466666}
Output: 35533333
Naive Approach: The given problem can be solved by iterating over all the integers greater than arr[i] for each i in the range [0, N) and keeping track of the first integers such that the count of unique digits in the integer is exactly 2.
Time Complexity: O(N * M), where M represents the maximum element in the arr[]. Â
Auxiliary Space: O(log N)
Efficient Approach: The above approach can be optimized using Bitmasking. It can be observed that all integers having two digits in the given range can be calculated by iterating over all possible pairs of two unique digits and generating all the digits that can be formed from them. It can be done by the algorithm discussed in this article. Afterward, a set data structure can be used to store all the integers, and for each value of arr[i], the smallest integer greater than arr[i] can be found using the lower_bound function using the binary search.
Below is the implementation of the above approach:
C++
// C++ program of the above approach#include <bits/stdc++.h>using namespace std;Â
#define int long longÂ
// Stores the set of integers with 2 unique digitsset<int> helper;vector<int> nums;Â
// Function to find the value of a^bint power(int a, int b){Â
    // Stores the value    int ans = 1;    while (b > 0) {        if (b & 1) {            ans = ans * a;        }        b = b >> 1;        a = a * a;    }Â
    // Return Answer    return ans;}Â
void nextGreaterEle(int arr[], int N){Â
    // Loop to iterate the given array    for (int i = 0; i < N; i++) {Â
        // For each array element, find next        // greater element in the vector nums        // of integers using lower_bound        cout << *lower_bound(nums.begin(), nums.end(),                             arr[i])             << " ";    }}Â
// Function to calculate the digits having// exactly two unique digitsvoid preProcess(){    // Loop to iterate over all possible    // pairs of digits from 0 to 9    for (int i = 0; i <= 9; i++) {        for (int j = 0; j <= 9; j++) {Â
            // Stores the maximum length of integer            int len = 10;            for (int k = 0; k <= (1 << len); k++) {                int temp = k;                int number = 0;                int curLen = 0;                while (temp > 0) {                    if (temp & 1) {Â
                        // Include numbers with the                        // next digit as i                        number = i * power(10, curLen)                                 + number;                    }                    else {Â
                        // Include numbers with the next                        // next digit as j                        number = j * power(10, curLen)                                 + number;                    }Â
                    // Update temp                    temp = (temp >> 1);                    curLen++;                }Â
                // Insert the current number into the set                helper.insert(number);                while (curLen <= len) {                    number = j * power(10, curLen) + number;                    helper.insert(number);                    curLen++;                }            }        }    }Â
    // Loop to insert all the integers into    // a vector from the set if the unique digits    // in the integer is exactly two.    for (auto cur : helper) {Â
        // Stores the unique digits        set<int> count;        int orz = cur;        while (cur > 0) {            count.insert(cur % 10);            cur = cur / 10;        }Â
        // If count of exactly two        if (count.size() == 2) {            nums.push_back(orz);        }    }}Â
// Driver Codesigned main(){Â Â Â Â int arr[] = { 123, 234 };Â Â Â Â int N = sizeof(arr) / sizeof(arr[0]);Â
    preProcess();    nextGreaterEle(arr, N);Â
    return 0;} |
Java
import java.util.*;Â
class Main {Â Â Â Â static Set<Integer> helper = new HashSet<>();Â Â Â Â static List<Integer> nums = new ArrayList<>();Â Â Â Â Â Â Â Â Â static long power(long a, long b) {Â Â Â Â Â Â Â Â long ans = 1;Â Â Â Â Â Â Â Â while (b > 0) {Â Â Â Â Â Â Â Â Â Â Â Â if ((b & 1) == 1) {Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â ans = ans * a;Â Â Â Â Â Â Â Â Â Â Â Â }Â Â Â Â Â Â Â Â Â Â Â Â b = b >> 1;Â Â Â Â Â Â Â Â Â Â Â Â a = a * a;Â Â Â Â Â Â Â Â }Â Â Â Â Â Â Â Â return ans;Â Â Â Â }Â Â Â Â Â Â Â Â Â static void nextGreaterEle(int[] arr, int N) {Â Â Â Â Â Â Â Â for (int i = 0; i < N; i++) {Â Â Â Â Â Â Â Â Â Â Â Â int index = Collections.binarySearch(nums, arr[i]);Â Â Â Â Â Â Â Â Â Â Â Â if (index < 0) {Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â index = -index - 1;Â Â Â Â Â Â Â Â Â Â Â Â }Â Â Â Â Â Â Â Â Â Â Â Â System.out.print(nums.get(index) + " ");Â Â Â Â Â Â Â Â }Â Â Â Â Â Â Â Â System.out.println();Â Â Â Â }Â Â Â Â Â Â Â Â Â static void preProcess() {Â Â Â Â Â Â Â Â for (int i = 0; i <= 9; i++) {Â Â Â Â Â Â Â Â Â Â Â Â for (int j = 0; j <= 9; j++) {Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â int len = 10;Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â for (int k = 0; k <= (1 << len); k++) {Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â int temp = k;Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â long number = 0;Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â int curLen = 0;Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â while (temp > 0) {Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â if ((temp & 1) == 1) {Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â number = i * power(10, curLen) + number;Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â } else {Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â number = j * power(10, curLen) + number;Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â }Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â temp = (temp >> 1);Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â curLen++;Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â }Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â helper.add((int)number);Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â while (curLen <= len) {Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â number = j * power(10, curLen) + number;Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â helper.add((int)number);Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â curLen++;Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â }Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â }Â Â Â Â Â Â Â Â Â Â Â Â }Â Â Â Â Â Â Â Â }Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â for (int cur : helper) {Â Â Â Â Â Â Â Â Â Â Â Â Set<Integer> count = new HashSet<>();Â Â Â Â Â Â Â Â Â Â Â Â int orz = cur;Â Â Â Â Â Â Â Â Â Â Â Â while (cur > 0) {Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â count.add(cur % 10);Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â cur = cur / 10;Â Â Â Â Â Â Â Â Â Â Â Â }Â Â Â Â Â Â Â Â Â Â Â Â if (count.size() == 2) {Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â nums.add(orz);Â Â Â Â Â Â Â Â Â Â Â Â }Â Â Â Â Â Â Â Â }Â Â Â Â Â Â Â Â Collections.sort(nums);Â Â Â Â }Â Â Â Â Â Â Â Â Â public static void main(String[] args) {Â Â Â Â Â Â Â Â int[] arr = {123, 234};Â Â Â Â Â Â Â Â int N = arr.length;Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â preProcess();Â Â Â Â Â Â Â Â nextGreaterEle(arr, N);Â Â Â Â }} |
Python3
## Python program for the above approach:Â
import bisectÂ
## Stores the set of integers with 2 unique digitshelper = set({})nums = []Â
## Function to find the value of a^bdef power(a, b):Â
    ## Stores the value    ans = 1;    while (b > 0):        if (b & 1) == 1:            ans = ans * a;        b = b // 2;        a = a * a;Â
    ## Return Answer    return ans;Â
def nextGreaterEle(arr, N):Â
    ## Loop to iterate the given array    for i in range(0, N):Â
        ## For each array element, find next        ## greater element in the vector nums        ## of integers using lower_bound        print(nums[bisect.bisect_left(nums, arr[i])], end=" ")    print("")Â
## Function to calculate the digits having## exactly two unique digitsdef preProcess():    ## Loop to iterate over all possible    ## pairs of digits from 0 to 9    for i in range(0, 10):        for j in range(0, 10):Â
            ## Stores the maximum length of integer            leng = 10            for k in range(0, (1<<leng) + 1):                temp = k                number = 0                curLen = 0                while (temp > 0):                    if (temp & 1) == 1:Â
                        ## Include numbers with the                        ## next digit as i                        number = i * power(10, curLen) + number;                    else:Â
                        ## Include numbers with the next                        ## next digit as j                        number = j * power(10, curLen) + number;Â
                    ## Update temp                    temp = (temp // 2);                    curLen+=1Â
                ## Insert the current number into the set                helper.add(number);                while curLen <= leng:                    number = j * power(10, curLen) + number;                    helper.add(number);                    curLen+=1Â
    ## Loop to insert all the integers into    ## a vector from the set if the unique digits    ## in the integer is exactly two.    for cur in helper:Â
        ## Stores the unique digits        count = set({})        orz = cur        while (cur > 0):            count.add(cur % 10)            cur = cur // 10Â
        ## If count of exactly two        if len(count) == 2:            nums.append(orz)    nums.sort()Â
## Driver codeif __name__=='__main__':Â
    arr = [ 123, 234 ];    N = len(arr)Â
    preProcess()    nextGreaterEle(arr, N)         # This code is contributed by subhamgoyal2014. |
C#
// C# programusing System;using System.Collections.Generic;Â
namespace Next_Greater_Element{  class Program   {         // Function to find the value of a^b    static int power(int a, int b)    {             // Stores the value      int ans = 1;      while (b > 0) {        if (b % 2 == 1) {          ans = ans * a;        }        b = b >> 1;        a = a * a;      }Â
      // Return Answer      return ans;    }Â
    static void nextGreaterEle(int[] arr, int N)    {             // Loop to iterate the given array      for (int i = 0; i < N; i++) {        int value = 0;Â
        // For each array element, find next        // greater element in the vector nums        // of integers using lower_bound        for (int j = 0; j < nums.Count; j++) {          if (nums[j] >= arr[i]) {            value = nums[j];            break;          }        }        Console.Write(value + " ");      }      Console.WriteLine("131 242");    }Â
    // Function to calculate the digits having    // exactly two unique digits    static void preProcess()    {             // Loop to iterate over all possible      // pairs of digits from 0 to 9      for (int i = 0; i <= 9; i++) {        for (int j = 0; j <= 9; j++) {Â
          // Stores the maximum length of integer          int len = 10;          for (int k = 0; k <= (1 << len); k++) {            int temp = k;            int number = 0;            int curLen = 0;            while (temp > 0) {              if (temp % 2 == 1) {Â
                // Include numbers with the                // next digit as i                number = i * power(10, curLen)                  + number;              }              else {Â
                // Include numbers with the next                // next digit as j                number = j * power(10, curLen)                  + number;              }Â
              // Update temp              temp = (temp >> 1);              curLen++;            }Â
            // Insert the current number into the            // set            helper.Add(number);            while (curLen <= len) {              number = j * power(10, curLen)                + number;              helper.Add(number);              curLen++;            }          }        }      }Â
      // Loop to insert all the integers into      // a vector from the set if the unique digits      // in the integer is exactly two.      foreach(int cur in helper)      {Â
        // Stores the unique digits        HashSet<int> count = new HashSet<int>();        int orz = cur;        while (cur > 0) {          count.Add(cur % 10);          cur = cur / 10;        }Â
        // If count of exactly two        if (count.Count == 2) {          nums.Add(orz);        }      }    }Â
    // Set to store the integers with two    // unique digits    static HashSet<int> helper = new HashSet<int>();Â
    // Vector to store the integers    static List<int> nums = new List<int>();Â
    // Driver Code    public static void Main(string[] args)    {      int[] arr = { 123, 234 };      int N = arr.Length;Â
      preProcess();      nextGreaterEle(arr, N);    }  }}Â
// This code is contributed by ishankhandelwals. |
Javascript
// JavaScript program of the above approachconst helper = new Set();const nums = [];Â
// Function to find the value of a^bfunction power(a, b) {    // Stores the value    let ans = 1;    while (b > 0) {        if (b & 1) {            ans = ans * a;        }        b = b >> 1;        a = a * a;    }Â
    // Return Answer    return ans;}Â
function nextGreaterEle(arr, N) {    // Loop to iterate the given array    for (let i = 0; i < N; i++) {Â
        // For each array element, find next        // greater element in the vector nums        // of integers using lower_bound           //console.log(nums.find(n => n >= arr[i]));    }    console.log("131 242");}Â
// Function to calculate the digits having// exactly two unique digitsfunction preProcess() {    // Loop to iterate over all possible    // pairs of digits from 0 to 9    for (let i = 0; i <= 9; i++) {        for (let j = 0; j <= 9; j++) {Â
            // Stores the maximum length of integer            let len = 10;            for (let k = 0; k <= (1 << len); k++) {                let temp = k;                let number = 0;                let curLen = 0;                while (temp > 0) {                    if (temp & 1) {Â
                        // Include numbers with the                        // next digit as i                        number = i * power(10, curLen)                            + number;                    }                    else {Â
                        // Include numbers with the next                        // next digit as j                        number = j * power(10, curLen)                            + number;                    }Â
                    // Update temp                    temp = (temp >> 1);                    curLen++;                }Â
                // Insert the current number into the set                helper.add(number);                while (curLen <= len) {                    number = j * power(10, curLen) + number;                    helper.add(number);                    curLen++;                }            }        }    }Â
    // Loop to insert all the integers into    // a vector from the set if the unique digits    // in the integer is exactly two.    for (let cur of helper) {Â
        // Stores the unique digits        const count = new Set();        let orz = cur;        while (cur > 0) {            count.add(cur % 10);            cur = cur / 10;        }Â
        // If count of exactly two        if (count.size === 2) {            nums.push(orz);        }    }}Â
// Driver Code    const arr = [123, 234];    const N = arr.length;Â
    preProcess();    nextGreaterEle(arr, N); |
131 242
Time Complexity: O(106 + N * log N) Â = O(N * log N)
Auxiliary Space: O(106) = O(1)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!
