Count Digit Appearances Problem
#3895
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3895.
You are given an integer array nums and an integer digit.
Return the total number of times digit appears in the decimal representation of all elements in nums.
Example 1:
Input: nums = [12,54,32,22], digit = 2
Output: 4
Explanation:
The digit 2 appears once in 12 and 32, and twice in 22. Thus, the total number of times digit 2 appears is 4.
Example 2:
Input: nums = [1,34,7], digit = 9
Output: 0
Explanation:
The digit 9 does not appear in the decimal representation of any element in nums, so the total number of times digit 9 appears is 0.
Constraints:
1 <= nums.length <= 10001 <= nums[i] <= 10^60 <= digit <= 9
Solution
Approach: Simulation
Go through every number and peel off its decimal digits one at a time: x % 10 is the last digit, and x / 10 drops it. Each time the digit equals digit, add one to the answer. Note that digit = 0 works too, because a number is only processed while it is positive, so leading zeros are never counted.
Complexity:
- Time complexity:
O(n log M), wherenis the length of the array andMis the largest value. - Space complexity:
O(1).
class Solution:
def countDigitOccurrences(self, nums: List[int], digit: int) -> int:
ans = 0
for x in nums:
while x:
v = x % 10
if v == digit:
ans += 1
x //= 10
return ans