#2283

Check if Number Has Equal Digit Count and Digit Value

Easy
Hash TableStringCountingHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

The optimal approach uses a single pass to count the occurrences of each digit in the string and then checks if the counts match the expected values. This is efficient because it reduces the number of iterations needed.

⚙️

Algorithm

4 steps
  1. 1Step 1: Create an array of size 10 (for digits 0-9) to count occurrences of each digit.
  2. 2Step 2: Iterate through the string and populate the count array based on the digits found.
  3. 3Step 3: Iterate through the string again, checking if the count of each digit matches the expected value from the string.
  4. 4Step 4: If all checks pass, return true; otherwise, return false.
solution.py8 lines
1def digitCount(num):
2    count = [0] * 10
3    for digit in num:
4        count[int(digit)] += 1
5    for i in range(len(num)):
6        if count[i] != int(num[i]):
7            return False
8    return True

Complexity note: The time complexity is O(n) because we make a single pass to count the digits and another pass to verify the counts, resulting in linear time. The space complexity is O(1) since the count array is fixed in size (10).

  • 1The digit at each index directly represents the expected count of that index's digit in the string.
  • 2Using a counting array allows for efficient frequency tracking without repeated string scans.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.