Find next greater number formed with exactly two unique digits for each Array element
Last Updated :
02 Feb, 2023
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 digits
set<int> helper;
vector<int> nums;
// Function to find the value of a^b
int 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 digits
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 & 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 Code
signed 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 digits
helper = set({})
nums = []
## Function to find the value of a^b
def 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 digits
def 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 code
if __name__=='__main__':
arr = [ 123, 234 ];
N = len(arr)
preProcess()
nextGreaterEle(arr, N)
# This code is contributed by subhamgoyal2014.
C#
// C# program
using 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 approach
const helper = new Set();
const nums = [];
// Function to find the value of a^b
function 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 digits
function 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);
Time Complexity: O(106 + N * log N) = O(N * log N)
Auxiliary Space: O(106) = O(1)
Similar Reads
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
Find the largest Number that can be formed with the given Digits Given an array of integers arr[] represents digits of a number. The task is to write a program to generate the largest number possible using these digits. Note: The digits in the array are between 0 and 9. That is, 0 < arr[i] < 9. Examples: Input: arr[] = {4, 7, 9, 2, 3}Output: Largest number:
10 min read
Find Next number having distinct digits from the given number N Given a natural number N, the task is to find the next number having distinct digits from the given number.Examples: Input: N = 19 Output: 20 Explanation: Next number to 19 whose digits are different from 19 is 20.Input: N = 2019 Output: 3333 Explanation: Next number to 2019 whose digits are differe
10 min read
Check if Arrays can be made equal by Replacing elements with their number of Digits Given two arrays A[] and B[] of length N, the task is to check if both arrays can be made equal by performing the following operation at most K times: Choose any index i and either change Ai to the number of digits Ai have or change Bi to the number of digits Bi have. Examples: Input: N = 4, K = 1,
10 min read
Count pairs in an array having sum of elements with their respective sum of digits equal Given an array arr[] consisting of N positive integers, the task is to count the number of pairs in the array, say (a, b) such that sum of a with its sum of digits is equal to sum of b with its sum of digits. Examples: Input: arr[] = {1, 1, 2, 2}Output: 2Explanation:Following are the pairs that sati
8 min read