Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Break down a hard problem into reliable checkpoints, edge-case handling, and complexity trade-offs.
Given an array of digits which is sorted in non-decreasing order. You can write numbers using each digits[i] as many times as we want. For example, if digits = ['1','3','5'], we may write numbers such as '13', '551', and '1351315'.
Return the number of positive integers that can be generated that are less than or equal to a given integer n.
Example 1:
Input: digits = ["1","3","5","7"], n = 100 Output: 20 Explanation: The 20 numbers that can be written are: 1, 3, 5, 7, 11, 13, 15, 17, 31, 33, 35, 37, 51, 53, 55, 57, 71, 73, 75, 77.
Example 2:
Input: digits = ["1","4","9"], n = 1000000000 Output: 29523 Explanation: We can write 3 one digit numbers, 9 two digit numbers, 27 three digit numbers, 81 four digit numbers, 243 five digit numbers, 729 six digit numbers, 2187 seven digit numbers, 6561 eight digit numbers, and 19683 nine digit numbers. In total, this is 29523 integers that can be written using the digits array.
Example 3:
Input: digits = ["7"], n = 8 Output: 1
Constraints:
1 <= digits.length <= 9digits[i].length == 1digits[i] is a digit from '1' to '9'.digits are unique.digits is sorted in non-decreasing order.1 <= n <= 109Problem summary: Given an array of digits which is sorted in non-decreasing order. You can write numbers using each digits[i] as many times as we want. For example, if digits = ['1','3','5'], we may write numbers such as '13', '551', and '1351315'. Return the number of positive integers that can be generated that are less than or equal to a given integer n.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Math · Binary Search · Dynamic Programming
["1","3","5","7"] 100
["1","4","9"] 1000000000
["7"] 8
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #902: Numbers At Most N Given Digit Set
class Solution {
private Set<Integer> nums = new HashSet<>();
private char[] s;
private Integer[] f;
public int atMostNGivenDigitSet(String[] digits, int n) {
s = String.valueOf(n).toCharArray();
f = new Integer[s.length];
for (var x : digits) {
nums.add(Integer.parseInt(x));
}
return dfs(0, true, true);
}
private int dfs(int i, boolean lead, boolean limit) {
if (i >= s.length) {
return lead ? 0 : 1;
}
if (!lead && !limit && f[i] != null) {
return f[i];
}
int up = limit ? s[i] - '0' : 9;
int ans = 0;
for (int j = 0; j <= up; ++j) {
if (j == 0 && lead) {
ans += dfs(i + 1, true, limit && j == up);
} else if (nums.contains(j)) {
ans += dfs(i + 1, false, limit && j == up);
}
}
if (!lead && !limit) {
f[i] = ans;
}
return ans;
}
}
// Accepted solution for LeetCode #902: Numbers At Most N Given Digit Set
func atMostNGivenDigitSet(digits []string, n int) int {
s := strconv.Itoa(n)
m := len(s)
f := make([]int, m)
for i := range f {
f[i] = -1
}
nums := map[int]bool{}
for _, d := range digits {
x, _ := strconv.Atoi(d)
nums[x] = true
}
var dfs func(i int, lead, limit bool) int
dfs = func(i int, lead, limit bool) int {
if i >= m {
if lead {
return 0
}
return 1
}
if !lead && !limit && f[i] != -1 {
return f[i]
}
up := 9
if limit {
up = int(s[i] - '0')
}
ans := 0
for j := 0; j <= up; j++ {
if j == 0 && lead {
ans += dfs(i+1, true, limit && j == up)
} else if nums[j] {
ans += dfs(i+1, false, limit && j == up)
}
}
if !lead && !limit {
f[i] = ans
}
return ans
}
return dfs(0, true, true)
}
# Accepted solution for LeetCode #902: Numbers At Most N Given Digit Set
class Solution:
def atMostNGivenDigitSet(self, digits: List[str], n: int) -> int:
@cache
def dfs(i: int, lead: int, limit: bool) -> int:
if i >= len(s):
return lead ^ 1
up = int(s[i]) if limit else 9
ans = 0
for j in range(up + 1):
if j == 0 and lead:
ans += dfs(i + 1, 1, limit and j == up)
elif j in nums:
ans += dfs(i + 1, 0, limit and j == up)
return ans
s = str(n)
nums = {int(x) for x in digits}
return dfs(0, 1, True)
// Accepted solution for LeetCode #902: Numbers At Most N Given Digit Set
/**
* [0902] Numbers At Most N Given Digit Set
*
* Given an array of digits which is sorted in non-decreasing order. You can write numbers using each digits[i] as many times as we want. For example, if digits = ['1','3','5'], we may write numbers such as '13', '551', and '1351315'.
* Return the number of positive integers that can be generated that are less than or equal to a given integer n.
*
* Example 1:
*
* Input: digits = ["1","3","5","7"], n = 100
* Output: 20
* Explanation:
* The 20 numbers that can be written are:
* 1, 3, 5, 7, 11, 13, 15, 17, 31, 33, 35, 37, 51, 53, 55, 57, 71, 73, 75, 77.
*
* Example 2:
*
* Input: digits = ["1","4","9"], n = 1000000000
* Output: 29523
* Explanation:
* We can write 3 one digit numbers, 9 two digit numbers, 27 three digit numbers,
* 81 four digit numbers, 243 five digit numbers, 729 six digit numbers,
* 2187 seven digit numbers, 6561 eight digit numbers, and 19683 nine digit numbers.
* In total, this is 29523 integers that can be written using the digits array.
*
* Example 3:
*
* Input: digits = ["7"], n = 8
* Output: 1
*
*
* Constraints:
*
* 1 <= digits.length <= 9
* digits[i].length == 1
* digits[i] is a digit from '1' to '9'.
* All the values in digits are unique.
* digits is sorted in non-decreasing order.
* 1 <= n <= 10^9
*
*/
pub struct Solution {}
// problem: https://leetcode.com/problems/numbers-at-most-n-given-digit-set/
// discuss: https://leetcode.com/problems/numbers-at-most-n-given-digit-set/discuss/?currentPage=1&orderBy=most_votes&query=
// submission codes start here
impl Solution {
pub fn at_most_n_given_digit_set(digits: Vec<String>, n: i32) -> i32 {
let digits: Vec<char> = digits.iter().map(|s| s.chars().next().unwrap()).collect();
let n = n.to_string();
let mut dp = vec![0; n.len() + 1];
dp[n.len()] = 1;
for (i, c) in n.chars().rev().enumerate() {
for &d in digits.iter() {
match d.cmp(&c) {
std::cmp::Ordering::Less => dp[n.len() - i - 1] += digits.len().pow(i as u32),
std::cmp::Ordering::Equal => dp[n.len() - i - 1] += dp[n.len() - i],
std::cmp::Ordering::Greater => {}
}
}
}
(dp[0]
+ (1..n.len())
.map(|i| digits.len().pow(i as u32))
.sum::<usize>()) as i32
}
}
// submission codes end
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_0902_example_1() {
let digits = vec_string!["1", "3", "5", "7"];
let n = 100;
let result = 20;
assert_eq!(Solution::at_most_n_given_digit_set(digits, n), result);
}
#[test]
fn test_0902_example_2() {
let digits = vec_string!["1", "4", "9"];
let n = 1000000000;
let result = 29523;
assert_eq!(Solution::at_most_n_given_digit_set(digits, n), result);
}
#[test]
fn test_0902_example_3() {
let digits = vec_string!["7"];
let n = 8;
let result = 1;
assert_eq!(Solution::at_most_n_given_digit_set(digits, n), result);
}
}
// Accepted solution for LeetCode #902: Numbers At Most N Given Digit Set
function atMostNGivenDigitSet(digits: string[], n: number): number {
const s = n.toString();
const m = s.length;
const f: number[] = Array(m).fill(-1);
const nums = new Set<number>(digits.map(d => parseInt(d)));
const dfs = (i: number, lead: boolean, limit: boolean): number => {
if (i >= m) {
return lead ? 0 : 1;
}
if (!lead && !limit && f[i] !== -1) {
return f[i];
}
const up = limit ? +s[i] : 9;
let ans = 0;
for (let j = 0; j <= up; ++j) {
if (!j && lead) {
ans += dfs(i + 1, true, limit && j === up);
} else if (nums.has(j)) {
ans += dfs(i + 1, false, limit && j === up);
}
}
if (!lead && !limit) {
f[i] = ans;
}
return ans;
};
return dfs(0, true, true);
}
Use this to step through a reusable interview workflow for this problem.
Check every element from left to right until we find the target or exhaust the array. Each comparison is O(1), and we may visit all n elements, giving O(n). No extra space needed.
Each comparison eliminates half the remaining search space. After k comparisons, the space is n/2ᵏ. We stop when the space is 1, so k = log₂ n. No extra memory needed — just two pointers (lo, hi).
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: Temporary multiplications exceed integer bounds.
Usually fails on: Large inputs wrap around unexpectedly.
Fix: Use wider types, modular arithmetic, or rearranged operations.
Wrong move: Setting `lo = mid` or `hi = mid` can stall and create an infinite loop.
Usually fails on: Two-element ranges never converge.
Fix: Use `lo = mid + 1` or `hi = mid - 1` where appropriate.
Wrong move: An incomplete state merges distinct subproblems and caches incorrect answers.
Usually fails on: Correctness breaks on cases that differ only in hidden state.
Fix: Define state so each unique subproblem maps to one DP cell.