Check Digitorial Permutation Problem
#3848
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 3848.
You are given an integer n.
A number is called digitorial if the sum of the factorials of its digits is equal to the number itself.
Determine whether any permutation of n (including the original order) forms a digitorial number.
Return true if such a permutation exists, otherwise return false.
Note:
- The factorial of a non-negative integer
x, denoted asx!, is the product of all positive integers less than or equal tox, and0! = 1. - A permutation is a rearrangement of all the digits of a number that does not start with zero. Any arrangement starting with zero is invalid.
Example 1:
Input: n = 145
Output: true
Explanation:
The number 145 itself is digitorial since 1! + 4! + 5! = 1 + 24 + 120 = 145. Thus, the answer is true.
Example 2:
Input: n = 10
Output: false
Explanation:
10 is not digitorial since 1! + 0! = 2 is not equal to 10, and the permutation "01" is invalid because it starts with zero.
Constraints:
1 <= n <= 10^9
Solution
Approach: Simulation
Rearranging the digits of n does not change the sum of the factorials of its digits. So it is enough to compute that sum once and check whether its digits are a permutation of the digits of n, which we do by comparing the two sorted digit strings. Factorials of 0 to 9 are precomputed.
Complexity: O(log n) time and O(1) extra space (the factorial table has 10 entries).
from functools import lru_cache
@lru_cache(None)
def f(x: int) -> int:
if x < 2:
return 1
return x * f(x - 1)
class Solution:
def isDigitorialPermutation(self, n: int) -> bool:
x, y = 0, n
while y:
x += f(y % 10)
y //= 10
return sorted(str(x)) == sorted(str(n))