Facebook Pixel

3895. Count Digit Appearances

Medium
LeetCode ↗

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] and digit = 2.
  • In 12, the digit 2 appears 1 time.
  • In 123, the digit 2 appears 1 time.
  • In 21, the digit 2 appears 1 time.
  • The total count is 1 + 1 + 1 = 3, so the answer is 3.

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.

Quick Interview Experience
Help others by sharing your interview experience
Have you seen this problem before?

How We Pick the Algorithm

Why Simulation / Basic DSA?

This problem maps to Simulation / Basic DSA through a short path in the full flowchart.

DirecttransformationoryesComplexdatastructure?noSimulation /Basic DSA

Following the described procedure step by step produces the solution.

Open in Flowchart

Intuition

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 % 10 gives us the last digit of x. For example, 123 % 10 = 3.
  • Doing x // 10 removes the last digit from x. 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 % 10 to grab the last digit of x.
  • We compare v with digit. If v == digit, we found one occurrence, so we do ans += 1.
  • We then run x //= 10 to 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), where n is the number of elements in nums and d is 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, and v) 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:

Iterationx (current)v = x % 10v == 2?ans afterx //= 10
1122✅ Yes11
211❌ No10

The while x: loop stops because x is now 0. From 12, we found the digit 2 once, so ans = 1.


Processing x = 123:

Iterationx (current)v = x % 10v == 2?ans afterx //= 10
11233❌ No112
2122✅ Yes21
311❌ No20

From 123, we found the digit 2 once, so ans = 2.


Processing x = 21:

Iterationx (current)v = x % 10v == 2?ans afterx //= 10
1211❌ No22
222✅ Yes30

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
22
1class 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}
27
1class 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};
21
1/**
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}
26

Time and Space Complexity

  • Time complexity: O(n × log₁₀ M). Here, n is the length of the array nums, and M is the maximum value in the array. The outer loop iterates over all n elements, and for each element x, the inner while loop runs once per digit of x. The number of digits in x is O(log₁₀ x), which is bounded by O(log₁₀ M). Therefore, the total time complexity is O(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] and digit = 0.
  • For 0: the while num: loop is skipped, so 0 contributes 0 (incorrectly — it should contribute 1).
  • For 10: the digit 0 is counted once.
  • For 5: no 0 found.
  • The code returns 1, but the correct answer is 2.

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 = -123 and digit = 3, you would expect to count the 3, 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 (09). 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 Roadmap
Discover Your Strengths and Weaknesses: Take Our 5-Minute Quiz to Get a Personalized Study Roadmap:

What 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

Want a Structured Path to Master System Design Too? Don’t Miss This!

Load More