1795. Digit Shuffle Multiples
A safe uses a numeric code. A locksmith has the digits of num on tiles and may place all of them in any order to form a new code. A code may not start with the digit 0, unless num is a single digit, in which case that digit stands alone. Two arrangements that read the same, which happens when num has repeated digits, are one code.
Return how many distinct codes can be formed from all digits of num that are divisible by d. Build the code one position at a time by choosing which digit value to place, keeping a count of how many tiles remain for each digit 0 to 9 and the value of the code so far modulo d; because you pick digit values rather than tile positions, every distinct code is built exactly once. The result is at most 9! = 362880, so it fits an int. Time is O(L! * 10) in the worst case with L = num.length at most 9, and space is O(L).
Example 1
- Input:
- num = "123", d = 3
- Output:
- 6
- Explanation:
All six arrangements have digit sum 6, so each is divisible by 3 and the count is 6.
Example 2
- Input:
- num = "100", d = 10
- Output:
- 1
- Explanation:
Of 100, 010 and 001 only 100 has no leading zero, and it is divisible by 10, so the count is 1.
Example 3
- Input:
- num = "1122", d = 7
- Output:
- 1
- Explanation:
The six distinct codes 1122, 1212, 1221, 2112, 2121 and 2211 are tested against 7; the count is 1.
Constraints
1 ≤ num.length ≤ 9; num has no leading zero
num contains only the characters '0' to '9'
1 ≤ d ≤ 1000
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
- Time per case
- Python 3,200 msC++ 800 msJava 1,600 msJavaScript 1,600 msTypeScript 1,600 ms
Expected complexity
- Time
- O(L! * 10)
- Space
- O(L)