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.
Given an integer n, count the total number of digit 1 appearing in all non-negative integers less than or equal to n.
Example 1:
Input: n = 13 Output: 6
Example 2:
Input: n = 0 Output: 0
Constraints:
0 <= n <= 109Problem summary: Given an integer n, count the total number of digit 1 appearing in all non-negative integers less than or equal to n.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Math · Dynamic Programming
13
0
factorial-trailing-zeroes)digit-count-in-range)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #233: Number of Digit One
class Solution {
private int m;
private char[] s;
private Integer[][] f;
public int countDigitOne(int n) {
s = String.valueOf(n).toCharArray();
m = s.length;
f = new Integer[m][m];
return dfs(0, 0, true);
}
private int dfs(int i, int cnt, boolean limit) {
if (i >= m) {
return cnt;
}
if (!limit && f[i][cnt] != null) {
return f[i][cnt];
}
int up = limit ? s[i] - '0' : 9;
int ans = 0;
for (int j = 0; j <= up; ++j) {
ans += dfs(i + 1, cnt + (j == 1 ? 1 : 0), limit && j == up);
}
if (!limit) {
f[i][cnt] = ans;
}
return ans;
}
}
// Accepted solution for LeetCode #233: Number of Digit One
func countDigitOne(n int) int {
s := strconv.Itoa(n)
m := len(s)
f := make([][]int, m)
for i := range f {
f[i] = make([]int, m)
for j := range f[i] {
f[i][j] = -1
}
}
var dfs func(i, cnt int, limit bool) int
dfs = func(i, cnt int, limit bool) int {
if i >= m {
return cnt
}
if !limit && f[i][cnt] != -1 {
return f[i][cnt]
}
up := 9
if limit {
up = int(s[i] - '0')
}
ans := 0
for j := 0; j <= up; j++ {
t := 0
if j == 1 {
t = 1
}
ans += dfs(i+1, cnt+t, limit && j == up)
}
if !limit {
f[i][cnt] = ans
}
return ans
}
return dfs(0, 0, true)
}
# Accepted solution for LeetCode #233: Number of Digit One
class Solution:
def countDigitOne(self, n: int) -> int:
@cache
def dfs(i: int, cnt: int, limit: bool) -> int:
if i >= len(s):
return cnt
up = int(s[i]) if limit else 9
ans = 0
for j in range(up + 1):
ans += dfs(i + 1, cnt + (j == 1), limit and j == up)
return ans
s = str(n)
return dfs(0, 0, True)
// Accepted solution for LeetCode #233: Number of Digit One
struct Solution;
impl Solution {
fn count_digit_one(n: i32) -> i32 {
let mut m = 1i64;
let mut res = 0i64;
let n = n as i64;
while m <= n {
let d = 10 * m;
res += n / d * m + m.min(0.max(n % d - m + 1));
m *= 10;
}
res as i32
}
}
#[test]
fn test() {
let n = 13;
let res = 6;
assert_eq!(Solution::count_digit_one(n), res);
}
// Accepted solution for LeetCode #233: Number of Digit One
function countDigitOne(n: number): number {
const s = n.toString();
const m = s.length;
const f: number[][] = Array.from({ length: m }, () => Array(m).fill(-1));
const dfs = (i: number, cnt: number, limit: boolean): number => {
if (i >= m) {
return cnt;
}
if (!limit && f[i][cnt] !== -1) {
return f[i][cnt];
}
const up = limit ? +s[i] : 9;
let ans = 0;
for (let j = 0; j <= up; ++j) {
ans += dfs(i + 1, cnt + (j === 1 ? 1 : 0), limit && j === up);
}
if (!limit) {
f[i][cnt] = ans;
}
return ans;
};
return dfs(0, 0, 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.