Check if Number Has Equal Digit Count and Digit Value — LeetCode 2283 Python Solution

EasyHash TableStringCounting
Problem
#2283
Pattern
Hash Map
Reading time
2 min

The problem

You are given a 0-indexed string num of length n consisting of digits. Return true if for every index i in the range 0 <= i < n, the digit i occurs num[i] times in num, otherwise return false.

Example

Input
num = "1210"
Output
true
Explanation
num[0] = '1'. The digit 0 occurs once in num.

Python solution

Python
class Solution:
    def digitCount(self, num: str) -> bool:
        cnt = Counter(int(x) for x in num)
        return all(cnt[i] == int(x) for i, x in enumerate(num))

Complexity

MeasureComplexity
TimeO(n)
SpaceO(|\Sigma|) auxiliary

Pattern: Hash Map

Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 2283. Check if Number Has Equal Digit Count and Digit Value is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Hash Table and Counting.

The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2283. Check if Number Has Equal Digit Count and Digit Value?
LeetCode 2283. Check if Number Has Equal Digit Count and Digit Value is rated Easy on LeetCode.
What is the time complexity of LeetCode 2283. Check if Number Has Equal Digit Count and Digit Value?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 2283. Check if Number Has Equal Digit Count and Digit Value?
The Python solution on this page uses O(|\Sigma|) auxiliary space.
What topics does LeetCode 2283. Check if Number Has Equal Digit Count and Digit Value cover?
LeetCode 2283. Check if Number Has Equal Digit Count and Digit Value is tagged Hash Table, String and Counting on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview