Ctrl K

Nobody Gets Their Own Gift

Medium
n guests came to a holiday party, each bringing one gift. The gifts go into a sack and are handed out again: every guest receives exactly one gift, but nobody may receive the one they brought. In how many ways can the gifts be handed out? The answer can be huge, so return it modulo 10⁹ + 7.
Example 1
n=3 → 2

If guests 1, 2, 3 brought gifts 1, 2, 3, only the handouts (2, 3, 1) and (3, 1, 2) work.

Example 2
n=1 → 0

A single guest can only get their own gift back.

Example 3
n=4 → 9
Constraints
  • 1 ≤ n ≤ 10⁶
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsCounting Grid Routes MediumSegments on a Dotted Line MediumSorted Vowel Words MediumVowels Across All Pieces MediumWalks of Exactly k Steps Medium
loading Python…
Input
n=3
Expected
2

Run checks the first 3 tests in your browser. Submit checks all 27 tests on the server, hidden ones included.