3895. Count Digit Appearances
Problem Description
You are given an integer array nums and an integer digit.
You need to count how many times the digit digit appears across the decimal representations of all the numbers in the array nums.
For example, if a number in the array is 121 and digit is 1, then this single number contributes 2 to the count because the digit 1 appears twice in 121.
Return the total number of times digit appears when you look at every element in nums.
Example walkthrough:
- Suppose
nums = [12, 123, 21]anddigit = 2. - In
12, the digit2appears1time. - In
123, the digit2appears1time. - In
21, the digit2appears1time. - The total count is
1 + 1 + 1 = 3, so the answer is3.
In short, the task is to scan through each number digit by digit, check whether each digit equals digit, and add up all the matches.
How We Pick the Algorithm
Why Simulation / Basic DSA?
This problem maps to Simulation / Basic DSA through a short path in the full flowchart.
Following the described procedure step by step produces the solution.
Open in FlowchartIntuition
The core question is: how do we look at the individual digits of a number?
A natural way to extract the digits of an integer is to use the modulo and integer division operations:
- Taking
x % 10gives us the last digit ofx. For example,123 % 10 = 3. - Doing
x // 10removes the last digit fromx. For example,123 // 10 = 12.
By repeating these two steps, we can peel off the digits of a number one at a time, from right to left, until nothing is left (the number becomes 0).
So for each number in nums, we keep extracting its last digit and comparing it with digit. Every time the extracted digit equals digit, we have found one occurrence, so we add 1 to our running total.
Since the problem asks for the total count across all numbers, we simply repeat this process for every element in the array and accumulate the matches into a single answer. After processing every number, the accumulated total is exactly what we need to return.
Solution Approach
Solution 1: Simulation
We use a straightforward simulation approach, processing the numbers one by one and counting the matching digits.
Step 1: Set up the counter
We create a variable ans initialized to 0. This will hold the total number of times digit appears.
Step 2: Loop over each number
We traverse every element x in the array nums. For each x, we examine all of its digits.
Step 3: Extract digits one at a time
For the current number x, we use a while x: loop so that we keep going as long as x is not 0. Inside the loop:
- We compute
v = x % 10to grab the last digit ofx. - We compare
vwithdigit. Ifv == digit, we found one occurrence, so we doans += 1. - We then run
x //= 10to drop the last digit, moving on to the next digit.
This loop naturally stops once all digits have been removed and x becomes 0.
Step 4: Return the result
After all numbers have been processed, ans holds the complete count, so we return it.
Complexity Analysis:
- Time complexity:
O(n × d), wherenis the number of elements innumsanddis the maximum number of digits in any element. We examine each digit of each number once. - Space complexity:
O(1), since we only use a few extra variables (ans,x, andv) regardless of the input size.
This method requires no extra data structures, just simple arithmetic operations (% and //) to break each number into its digits.
Example Walkthrough
Let's trace through the Simulation approach with a small example.
Input: nums = [12, 123, 21] and digit = 2
Step 1: Set up the counter
We start with ans = 0.
Step 2 & 3: Loop over each number and extract digits
Processing x = 12:
| Iteration | x (current) | v = x % 10 | v == 2? | ans after | x //= 10 |
|---|---|---|---|---|---|
| 1 | 12 | 2 | ✅ Yes | 1 | 1 |
| 2 | 1 | 1 | ❌ No | 1 | 0 |
The while x: loop stops because x is now 0. From 12, we found the digit 2 once, so ans = 1.
Processing x = 123:
| Iteration | x (current) | v = x % 10 | v == 2? | ans after | x //= 10 |
|---|---|---|---|---|---|
| 1 | 123 | 3 | ❌ No | 1 | 12 |
| 2 | 12 | 2 | ✅ Yes | 2 | 1 |
| 3 | 1 | 1 | ❌ No | 2 | 0 |
From 123, we found the digit 2 once, so ans = 2.
Processing x = 21:
| Iteration | x (current) | v = x % 10 | v == 2? | ans after | x //= 10 |
|---|---|---|---|---|---|
| 1 | 21 | 1 | ❌ No | 2 | 2 |
| 2 | 2 | 2 | ✅ Yes | 3 | 0 |
From 21, we found the digit 2 once, so ans = 3.
Step 4: Return the result
After processing every number, ans = 3.
Output: 3
This matches our expectation: the digit 2 appears once in each of 12, 123, and 21, giving a total of 1 + 1 + 1 = 3. Notice how the % operation peels digits from right to left, while // shrinks the number until it reaches 0 and the inner loop terminates.
Solution Implementation
1class Solution:
2 def countDigitOccurrences(self, nums: list[int], digit: int) -> int:
3 # Counter for how many times `digit` appears across all numbers
4 count = 0
5
6 # Examine each number in the input list
7 for num in nums:
8 # Extract digits one by one until the number becomes 0
9 while num:
10 # Get the least significant digit
11 current_digit = num % 10
12
13 # If it matches the target digit, increment the counter
14 if current_digit == digit:
15 count += 1
16
17 # Remove the least significant digit
18 num //= 10
19
20 # Return the total occurrence count
21 return count
221class Solution {
2 /**
3 * Counts how many times a specific digit appears across all numbers in the array.
4 *
5 * @param nums the array of integers to scan
6 * @param digit the digit (0-9) to count occurrences of
7 * @return the total number of times {@code digit} appears in all elements of {@code nums}
8 */
9 public int countDigitOccurrences(int[] nums, int digit) {
10 // Accumulator for the total count of the target digit.
11 int ans = 0;
12
13 // Iterate over every number in the array.
14 for (int num : nums) {
15 // Extract digits from right to left by repeatedly dividing by 10.
16 for (int x = num; x > 0; x /= 10) {
17 // Check whether the current least-significant digit matches the target.
18 if (x % 10 == digit) {
19 ++ans;
20 }
21 }
22 }
23
24 return ans;
25 }
26}
271class Solution {
2public:
3 // Count the total number of times a given digit appears across all numbers in nums.
4 int countDigitOccurrences(vector<int>& nums, int digit) {
5 int count = 0; // Accumulates the total occurrences of `digit`.
6
7 // Iterate over every number in the input vector.
8 for (int num : nums) {
9 // Extract digits one by one from the least significant end.
10 for (; num > 0; num /= 10) {
11 // If the current last digit matches the target, increment the counter.
12 if (num % 10 == digit) {
13 ++count;
14 }
15 }
16 }
17
18 return count; // Return the final tally.
19 }
20};
211/**
2 * Counts the total number of times a specific digit appears
3 * across all numbers in the given array.
4 *
5 * @param nums - The array of non-negative integers to inspect.
6 * @param digit - The single digit (0-9) to count occurrences of.
7 * @returns The total count of how many times `digit` appears.
8 */
9function countDigitOccurrences(nums: number[], digit: number): number {
10 // Running total of digit occurrences across all numbers.
11 let count = 0;
12
13 // Examine each number in the input array.
14 for (const num of nums) {
15 // Strip the number digit by digit from least significant to most.
16 for (let value = num; value > 0; value = Math.floor(value / 10)) {
17 // Extract the last digit and compare it to the target digit.
18 if (value % 10 === digit) {
19 ++count;
20 }
21 }
22 }
23
24 return count;
25}
26Time and Space Complexity
-
Time complexity:
O(n × log₁₀ M). Here,nis the length of the arraynums, andMis the maximum value in the array. The outer loop iterates over allnelements, and for each elementx, the innerwhileloop runs once per digit ofx. The number of digits inxisO(log₁₀ x), which is bounded byO(log₁₀ M). Therefore, the total time complexity isO(n × log₁₀ M). -
Space complexity:
O(1). Only a constant number of extra variables (ans,x,v) are used, regardless of the input size.
Common Pitfalls
Pitfall 1: Failing to count the digit 0 in numbers that are exactly 0
The most subtle bug in this solution comes from the loop condition while num:. When num is 0, the loop body never executes because 0 is falsy in Python. This means that if digit is 0 and the array contains the value 0, that occurrence will be missed entirely.
Example of the bug:
- Suppose
nums = [0, 10, 5]anddigit = 0. - For
0: thewhile num:loop is skipped, so0contributes0(incorrectly — it should contribute1). - For
10: the digit0is counted once. - For
5: no0found. - The code returns
1, but the correct answer is2.
Why it happens:
The while x: idiom is a convenient way to peel off digits, but it implicitly assumes that the number has at least one "real" digit to process. The number 0 is special: it is a single digit 0, yet its truthiness check immediately terminates the loop.
Solution:
Use a do-while style loop that guarantees the body runs at least once, so the single 0 digit gets processed:
class Solution:
def countDigitOccurrences(self, nums: list[int], digit: int) -> int:
count = 0
for num in nums:
# Guarantee the loop runs at least once to handle num == 0
while True:
current_digit = num % 10
if current_digit == digit:
count += 1
num //= 10
if num == 0:
break
return count
Alternatively, convert each number to a string, which naturally handles 0 as the single character "0":
class Solution:
def countDigitOccurrences(self, nums: list[int], digit: int) -> int:
target = str(digit)
return sum(str(num).count(target) for num in nums)
Pitfall 2: Not handling negative numbers
If the problem allows negative values in nums, the arithmetic approach can behave unexpectedly. In Python, -123 % 10 returns 7 (not 3) and -123 // 10 returns -13 (floor division rounds toward negative infinity), so the digit extraction breaks down completely.
Example of the bug:
- For
num = -123anddigit = 3, you would expect to count the3, but-123 % 10 == 7, so the count is wrong, and the loop may not even terminate cleanly the way you'd expect.
Solution:
Take the absolute value before processing, since the sign does not affect which digits appear:
class Solution:
def countDigitOccurrences(self, nums: list[int], digit: int) -> int:
count = 0
for num in nums:
num = abs(num) # Strip the sign before extracting digits
while True:
if num % 10 == digit:
count += 1
num //= 10
if num == 0:
break
return count
Pitfall 3: Misinterpreting digit as a multi-digit value
The logic current_digit = num % 10 only ever produces a single digit (0–9). If a caller mistakenly passes digit = 12, the comparison current_digit == digit will never be true, silently returning 0 instead of signaling an error.
Solution:
Validate the input range up front so the contract is explicit:
if not (0 <= digit <= 9): raise ValueError("digit must be a single decimal digit (0-9)")
This makes incorrect usage fail loudly rather than producing a misleadingly "valid" answer of 0.
Ready to land your dream job?
Unlock your dream job with a 5-minute quiz for a personalized study roadmap!
Get My RoadmapWhat is the best way of checking if an element exists in an unsorted array once in terms of time complexity? Select the best that applies.
Recommended Readings
Coding Interview Patterns Your Personal Dijkstra's Algorithm to Landing Your Dream Job The goal of AlgoMonster is to help you get a job in the shortest amount of time possible in a data driven way We compiled datasets of tech interview problems and broke them down by patterns This way
Recursion If you prefer videos here's a video that explains recursion in a fun and easy way Recursion is one of the most important concepts in computer science Simply speaking recursion is the process of a function calling itself Using a real life analogy imagine a scenario where you invite your friends to lunch https assets algo monster recursion jpg You first call Ben and ask him
Runtime Overview When learning about algorithms and data structures you'll frequently encounter the term time complexity This concept is fundamental in computer science and offers insights into how long an algorithm takes to complete given a certain input size What is Time Complexity Time complexity describes how the time needed
Want a Structured Path to Master System Design Too? Don’t Miss This!