Overflow in intermediate arithmetic
Wrong move: Temporary multiplications exceed integer bounds.
Usually fails on: Large inputs wrap around unexpectedly.
Fix: Use wider types, modular arithmetic, or rearranged operations.
Break down a hard problem into reliable checkpoints, edge-case handling, and complexity trade-offs.
We call a positive integer special if all of its digits are distinct.
Given a positive integer n, return the number of special integers that belong to the interval [1, n].
Example 1:
Input: n = 20 Output: 19 Explanation: All the integers from 1 to 20, except 11, are special. Thus, there are 19 special integers.
Example 2:
Input: n = 5 Output: 5 Explanation: All the integers from 1 to 5 are special.
Example 3:
Input: n = 135 Output: 110 Explanation: There are 110 integers from 1 to 135 that are special. Some of the integers that are not special are: 22, 114, and 131.
Constraints:
1 <= n <= 2 * 109Problem summary: We call a positive integer special if all of its digits are distinct. Given a positive integer n, return the number of special integers that belong to the interval [1, n].
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Math · Dynamic Programming
20
5
135
count-numbers-with-unique-digits)k-th-smallest-in-lexicographical-order)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #2376: Count Special Integers
class Solution {
private char[] s;
private Integer[][] f;
public int countSpecialNumbers(int n) {
s = String.valueOf(n).toCharArray();
f = new Integer[s.length][1 << 10];
return dfs(0, 0, true, true);
}
private int dfs(int i, int mask, boolean lead, boolean limit) {
if (i >= s.length) {
return lead ? 0 : 1;
}
if (!limit && !lead && f[i][mask] != null) {
return f[i][mask];
}
int up = limit ? s[i] - '0' : 9;
int ans = 0;
for (int j = 0; j <= up; ++j) {
if ((mask >> j & 1) == 1) {
continue;
}
if (lead && j == 0) {
ans += dfs(i + 1, mask, true, limit && j == up);
} else {
ans += dfs(i + 1, mask | (1 << j), false, limit && j == up);
}
}
if (!limit && !lead) {
f[i][mask] = ans;
}
return ans;
}
}
// Accepted solution for LeetCode #2376: Count Special Integers
func countSpecialNumbers(n int) int {
s := strconv.Itoa(n)
m := len(s)
f := make([][1 << 10]int, m+1)
for i := range f {
for j := range f[i] {
f[i][j] = -1
}
}
var dfs func(int, int, bool, bool) int
dfs = func(i, mask int, lead, limit bool) int {
if i >= m {
if lead {
return 0
}
return 1
}
if !limit && !lead && f[i][mask] != -1 {
return f[i][mask]
}
up := 9
if limit {
up = int(s[i] - '0')
}
ans := 0
for j := 0; j <= up; j++ {
if mask>>j&1 == 1 {
continue
}
if lead && j == 0 {
ans += dfs(i+1, mask, true, limit && j == up)
} else {
ans += dfs(i+1, mask|1<<j, false, limit && j == up)
}
}
if !limit && !lead {
f[i][mask] = ans
}
return ans
}
return dfs(0, 0, true, true)
}
# Accepted solution for LeetCode #2376: Count Special Integers
class Solution:
def countSpecialNumbers(self, n: int) -> int:
@cache
def dfs(i: int, mask: int, lead: bool, limit: bool) -> int:
if i >= len(s):
return int(lead ^ 1)
up = int(s[i]) if limit else 9
ans = 0
for j in range(up + 1):
if mask >> j & 1:
continue
if lead and j == 0:
ans += dfs(i + 1, mask, True, limit and j == up)
else:
ans += dfs(i + 1, mask | 1 << j, False, limit and j == up)
return ans
s = str(n)
return dfs(0, 0, True, True)
// Accepted solution for LeetCode #2376: Count Special Integers
/**
* [2376] Count Special Integers
*/
pub struct Solution {}
// submission codes start here
use std::collections::HashMap;
impl Solution {
pub fn count_special_numbers(n: i32) -> i32 {
let n: Vec<i32> = n
.to_string()
.chars()
.map(|c| c.to_digit(10).unwrap() as i32)
.collect();
let mut result = 0;
let mut candidate = 9;
// 计算位数小于n的特殊整数
for i in 0..n.len() as i32 - 1 {
result += candidate;
candidate *= 9 - i
}
let mut memory: HashMap<i32, i32> = HashMap::new();
result += Self::dp(0, false, &mut memory, &n);
result
}
// mask 表示前缀中使用过的数字 使用二进制表示
// prefix_smaller 当前的前缀是否小于n的前缀
fn dp(
mask: i32,
prefix_smaller: bool,
memory: &mut HashMap<i32, i32>,
number: &Vec<i32>,
) -> i32 {
let used_bits = mask.count_ones() as usize;
if used_bits == number.len() {
return 1;
}
let key = mask * 2 + if prefix_smaller { 1 } else { 0 };
if !memory.contains_key(&key) {
let mut result = 0;
let lower_bound = if mask == 0 { 1 } else { 0 };
let upper_bound = if prefix_smaller { 9 } else { number[used_bits] };
for i in lower_bound..=upper_bound {
if mask >> i & 1 == 0 {
result += Self::dp(
mask | 1 << i,
prefix_smaller || i < upper_bound,
memory,
number,
);
}
}
memory.insert(key, result);
}
*memory.get(&key).unwrap()
}
}
// submission codes end
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_2376() {
assert_eq!(19, Solution::count_special_numbers(20));
assert_eq!(5, Solution::count_special_numbers(5));
assert_eq!(110, Solution::count_special_numbers(135));
}
}
// Accepted solution for LeetCode #2376: Count Special Integers
function countSpecialNumbers(n: number): number {
const s = n.toString();
const m = s.length;
const f: number[][] = Array.from({ length: m }, () => Array(1 << 10).fill(-1));
const dfs = (i: number, mask: number, lead: boolean, limit: boolean): number => {
if (i >= m) {
return lead ? 0 : 1;
}
if (!limit && !lead && f[i][mask] !== -1) {
return f[i][mask];
}
const up = limit ? +s[i] : 9;
let ans = 0;
for (let j = 0; j <= up; ++j) {
if ((mask >> j) & 1) {
continue;
}
if (lead && j === 0) {
ans += dfs(i + 1, mask, true, limit && j === up);
} else {
ans += dfs(i + 1, mask | (1 << j), false, limit && j === up);
}
}
if (!limit && !lead) {
f[i][mask] = ans;
}
return ans;
};
return dfs(0, 0, true, true);
}
Use this to step through a reusable interview workflow for this problem.
Pure recursion explores every possible choice at each step. With two choices per state (take or skip), the decision tree has 2ⁿ leaves. The recursion stack uses O(n) space. Many subproblems are recomputed exponentially many times.
Each cell in the DP table is computed exactly once from previously solved subproblems. The table dimensions determine both time and space. Look for the state variables — each unique combination of state values is one cell. Often a rolling array can reduce space by one dimension.
Review these before coding to avoid predictable interview regressions.
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: 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.