#3848
Check Digitorial Permutation
MediumMathCountingHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n!) | O(n) |
| Space | O(n) | O(1) |
💡
Intuition
Time O(n)Space O(1)
Precompute the factorials of digits 0-9, then calculate the sum of factorials of the digits of n. Check if this sum can be formed using the digits of n.
⚙️
Algorithm
3 steps- 1Step 1: Precompute factorials for digits 0-9.
- 2Step 2: Calculate the sum of the factorials of the digits of n.
- 3Step 3: Check if the digits of the sum match the digits of n (no leading zero).
solution.py6 lines
1from collections import Counter
2
3def is_digitorial(n):
4 factorials = [1] + [i * factorials[i-1] for i in range(1, 10)]
5 digit_sum = sum(factorials[int(d)] for d in str(n))
6 return Counter(str(digit_sum)) == Counter(str(n)) and str(digit_sum)[0] != '0'ℹ
Complexity note: The complexity is linear as we only compute factorials once and sum them in a single pass.
- 1Factorials grow quickly, limiting possible digitorial numbers.
- 2Only digits 0-9 matter for factorial calculations.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.