Count Digits Frequency - Problem

Given a positive integer, count how many times each digit (0-9) appears in the number.

Task: Return an array of size 10 where the index represents the digit (0-9) and the value at that index represents the frequency of that digit in the given number.

Example: For the number 1223, digit 1 appears once, digit 2 appears twice, digit 3 appears once, and all other digits appear zero times.

Input & Output

Example 1 — Basic Case
$ Input: num = 1223
Output: [0,1,2,1,0,0,0,0,0,0]
💡 Note: Digit 0 appears 0 times, digit 1 appears 1 time, digit 2 appears 2 times, digit 3 appears 1 time, digits 4-9 appear 0 times each
Example 2 — Single Digit
$ Input: num = 7
Output: [0,0,0,0,0,0,0,1,0,0]
💡 Note: Only digit 7 appears once, all other digits appear 0 times
Example 3 — With Zeros
$ Input: num = 1002
Output: [2,1,1,0,0,0,0,0,0,0]
💡 Note: Digit 0 appears 2 times, digit 1 appears 1 time, digit 2 appears 1 time

Constraints

  • 0 ≤ num ≤ 109
  • num is a non-negative integer

Visualization

Tap to expand
INPUTALGORITHMRESULT1223Number to analyze1Initialize frequency[10] = {0}2Extract digits: 3, 2, 2, 13Count: freq[1]++, freq[2]+=2, freq[3]++4Return frequency array[0,1,2,1,0,0,0,0,0,0]Index: digit valueValue: frequency count• Digit 1 appears 1 time• Digit 2 appears 2 times• Digit 3 appears 1 time• Other digits: 0 timesKey Insight:Use a fixed-size array (index = digit, value = frequency) to count each digit 0-9 in a single pass through the number.TutorialsPoint - Count Digits Frequency | Mathematical Approach
Asked in
Amazon 15 Google 12 Microsoft 8
34.7K Views
Medium Frequency
~8 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen