LeetCode 3895 - Count Digit Appearances

The problem asks us to count how many times a specific decimal digit appears when writing out every number in the array. We are given an integer array nums and a single digit between 0 and 9.

LeetCode Problem 3895

Difficulty: 🟡 Medium
Topics:

Solution

Problem Understanding

The problem asks us to count how many times a specific decimal digit appears when writing out every number in the array. We are given an integer array nums and a single digit between 0 and 9. For each number in the array, we inspect its decimal representation and count how many positions contain the target digit. The final answer is the sum of these counts across all elements.

For example, if the array is [12, 54, 32, 22] and the target digit is 2, then the digit appears once in 12, once in 32, and twice in 22, giving a total of four appearances.

The input size is relatively small. The array contains at most 1000 numbers, and each number is at most 10^6. Since every number contains at most seven decimal digits, even a straightforward digit-by-digit scan is very efficient. The constraints indicate that there is no need for sophisticated mathematical formulas or advanced data structures.

Several edge cases are worth considering. The target digit may not appear anywhere, in which case the answer should be zero. Some numbers may contain the digit multiple times, such as 222, and every occurrence must be counted. The digit itself may be 0, so the implementation must correctly count zeros that occur inside numbers like 1010. The problem guarantees that every number is positive, so there is no need to handle negative values.

Approaches

A brute-force solution converts every number into a string and scans each character. Whenever a character matches the target digit, the answer is incremented. This approach is correct because the decimal representation explicitly contains all digit occurrences. Although converting integers to strings introduces some overhead, the input size is small enough that the solution runs comfortably within limits.

A slightly more direct approach avoids string conversion and processes each number arithmetically. By repeatedly taking the remainder modulo 10, we extract the last digit and compare it with the target digit. Then we divide by 10 and continue until the number becomes zero. This method examines every digit exactly once and uses constant extra space.

The key observation is that every occurrence of the target digit corresponds to exactly one decimal position in some number. Therefore, inspecting each digit individually guarantees that no occurrence is missed and none is counted twice.

Approach Time Complexity Space Complexity Notes
Brute Force O(ND) O(D) Convert each number to a string and scan characters
Optimal O(ND) O(1) Process digits using modulo and division
N is the number of elements and D is the maximum number of digits per element

Algorithm Walkthrough

  1. Initialize a variable count to zero. This variable will accumulate the total number of appearances of the target digit.
  2. Iterate through every number in the array. Each number contributes independently to the final answer.
  3. For the current number, repeatedly extract its last digit using the modulo operator % 10. This gives the rightmost decimal digit.
  4. Compare the extracted digit with the target digit. If they are equal, increment count because one occurrence has been found.
  5. Remove the last digit by performing integer division by 10. This shifts the remaining digits to the right and allows the next digit to be processed.
  6. Continue until the number becomes zero, which means every decimal position has been examined.
  7. After all numbers have been processed, return count.

Why it works

The algorithm maintains the invariant that every digit already removed from a number has been examined exactly once. Since repeatedly applying modulo 10 and division by 10 visits all decimal positions, every occurrence of the target digit is counted exactly once. Therefore, the final count is correct.

Python Solution

class Solution:
    def countDigitOccurrences(self, nums: list[int], digit: int) -> int:
        total_count = 0

        for number in nums:
            current = number

            while current > 0:
                if current % 10 == digit:
                    total_count += 1
                current //= 10

        return total_count

The implementation begins by creating total_count, which stores the answer. Each number is processed independently. A temporary variable current is used so that the original number remains unchanged.

Inside the while loop, current % 10 extracts the last digit. If that digit matches the target digit, the answer is incremented. Integer division by 10 removes the processed digit. Once current reaches zero, all digits of that number have been examined, and the algorithm moves to the next number. After every element has been processed, the accumulated count is returned.

Go Solution

func countDigitOccurrences(nums []int, digit int) int {
    totalCount := 0

    for _, number := range nums {
        current := number

        for current > 0 {
            if current%10 == digit {
                totalCount++
            }
            current /= 10
        }
    }

    return totalCount
}

The Go implementation follows the same logic as the Python version. A range loop iterates through the slice, and integer arithmetic is used to extract digits. No additional memory allocations are required. Since all values are at most 10^6, integer overflow is not a concern. Nil slices and empty slices are handled naturally, although the problem guarantees that the array contains at least one element.

Worked Examples

Example 1

Input:

nums = [12, 54, 32, 22]
digit = 2

The algorithm proceeds as follows.

Number Digits Processed New Occurrences Total Count
12 2, 1 1 1
54 4, 5 0 1
32 2, 3 1 2
22 2, 2 2 4

The final answer is 4.

Example 2

Input:

nums = [1, 34, 7]
digit = 9
Number Digits Processed New Occurrences Total Count
1 1 0 0
34 4, 3 0 0
7 7 0 0

No digit equals 9, so the answer is 0.

Complexity Analysis

Measure Complexity Explanation
Time O(ND) Each digit of every number is examined once
Space O(1) Only a few variables are used

Here, N denotes the number of elements in the array and D denotes the maximum number of digits in a number. Since each digit is processed exactly once, the running time is proportional to the total number of digits across the input. The algorithm uses constant auxiliary memory.

Test Cases

# test cases

sol = Solution()

assert sol.countDigitOccurrences([12, 54, 32, 22], 2) == 4      # example 1
assert sol.countDigitOccurrences([1, 34, 7], 9) == 0            # example 2
assert sol.countDigitOccurrences([2], 2) == 1                   # single number containing digit
assert sol.countDigitOccurrences([111, 11], 1) == 5             # repeated occurrences
assert sol.countDigitOccurrences([2222], 2) == 4                # all digits match
assert sol.countDigitOccurrences([1010], 0) == 2                # counting zeros inside a number
assert sol.countDigitOccurrences([999999], 9) == 6              # maximum repetition
assert sol.countDigitOccurrences([123456, 789012], 0) == 1      # zero appears once
assert sol.countDigitOccurrences([1000000], 0) == 6             # many zeros
assert sol.countDigitOccurrences([5, 6, 7, 8], 1) == 0          # digit absent everywhere
Test Why
[12,54,32,22], digit=2 Verifies the first example
[1,34,7], digit=9 Verifies the second example
[2], digit=2 Smallest nontrivial input
[111,11], digit=1 Multiple occurrences across numbers
[2222], digit=2 Every digit matches
[1010], digit=0 Ensures zeros inside numbers are counted
[999999], digit=9 Heavy repetition
[123456,789012], digit=0 Single zero occurrence
[1000000], digit=0 Consecutive zeros
[5,6,7,8], digit=1 Target digit completely absent

Edge Cases

One important edge case occurs when the target digit never appears. A careless implementation might accidentally return an uninitialized value or count incorrectly. Since the algorithm increments the answer only when a match is found, the count naturally remains zero.

Another important case is when a number contains the digit multiple times. For example, 2222 contains four occurrences of the digit 2. The repeated modulo and division operations inspect each position independently, ensuring that every occurrence is counted.

A third case involves the digit 0. Numbers such as 1010 contain zeros in the middle or at the end. The arithmetic approach treats zero exactly like any other digit, so these occurrences are counted correctly. Because the problem guarantees that all numbers are positive, there is no ambiguity associated with the representation of zero itself.

Finally, numbers may contain many repeated digits, such as 1000000. The algorithm continues processing until the number becomes zero, so every position is visited and all six zeros are counted correctly.