[InterviewBit] Numbers of length N and value less than K

Numbers of length N and value less than K

  • Time : O(Alog10C)
  • Space : O(1)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
int helper(vector<int>& A, int len, int pos, string limit, bool fl) {
if(len == pos) return pos == limit.length() ? fl : 1;
if(pos >= limit.length()) return 0;
else {
if(fl) return pow(A.size(), limit.length() - pos);
int res = 0;
for(int i = 0; i < A.size() and A[i] <= limit[pos] - '0'; i++) {
if(pos == 0 and A[i] == 0 and limit.length() != 1) continue;
if(A[i] == (limit[pos] - '0')) res += helper(A,len,pos+1,limit,false);
else res += helper(A,len,pos+1,limit,true);
}
return res;
}
}
int Solution::solve(vector<int> &A, int B, int C) {
string s = to_string(C);
if(s.length() < B) return 0;
if(s.length() > B) return pow(A.size(), B - 1) * (B != 1 ? (A.size() - count(begin(A), end(A), 0)) : A.size());
return helper(A,B,0,s, false);
}
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/09/06/PS/interviewbit/numbers-of-length-n-and-value-less-than-k/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.