1443. Partial Mix-Up
After a coat-check mishap, n guests each receive one of the n coats at random, so the coats form a permutation of the guests. A guest is "lucky" when they get their own coat back.
Given n and k, return the number of permutations of n items in which exactly k guests are lucky, modulo 1000000007. If k > n, the answer is 0. Choose which k guests keep their coats, then count the arrangements of the remaining n - k guests in which nobody is lucky (the derangement counts satisfy D(0) = 1, D(1) = 0, D(m) = (m-1)(D(m-1) + D(m-2))). Intended time is O(n) with O(1) extra space.
Example 1
- Input:
- n = 3, k = 1
- Output:
- 3
- Explanation:
Pick the one fixed guest in 3 ways; the other two must swap, which is 1 way, so 3 * 1 = 3.
Example 2
- Input:
- n = 4, k = 0
- Output:
- 9
- Explanation:
With no fixed guest allowed, this is the number of derangements of 4 items, which is 9.
Example 3
- Input:
- n = 2, k = 5
- Output:
- 0
- Explanation:
k is larger than n, so no permutation can have 5 fixed points and the answer is 0.
Constraints
0 ≤ n ≤ 106
0 ≤ k ≤ 106
Answer modulo 1000000007. Products of residues exceed 253, so use BigInt or a split multiplication in JavaScript.
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Expected complexity
- Time
- O(n)
- Space
- O(1)