There is a sequence of such numbers that have unique digits but does not contain any 0 or 2. You are given a number N
, find the next number in a sequence that is larger than N
. If the number in a sequence is higher than 10e9
, return -1
For example: given 2020, the answer is 3145, for 1982 the answer is 1983, for 9879 the answer is 13456
There is a similar problem: Given a number, find the next higher number which has the exact same set of digits as the original number. But, they are not same.
The algorithm complexity must be linear. The time limit is 1 second.
I have a brute-force solution, but it is not fast enough:
#include <iostream>
#include <vector>
using namespace std;
bool check_year(long year) {
vector<int> counter(10);
while(0 < year) {
counter[year % 10] += 1;
year = year / 10;
}
if(counter[0] > 0 or counter[2] > 0) {
return false;
}
for(int i = 0; i < 10; i++) {
if(counter[i] > 1) {
return false;
}
}
return true;
}
int main() {
int year;
cin >> year;
for(long i = year; i < 10e9; i++) {
if(check_year(i)) {
cout << i << endl;
return 0;
}
}
cout << -1 << endl;
return 0;
}