Given a non-negative integer N return the number of swap permutations of length N
A swap permutation is obtained from the identical permutation (1, 2, 3, ..., N) by applying the swap operation multiple times
A swap operation consists of picking two different items from the permutation and swapping them
You are allowed to swap an item at most once
Example:
Input: N = 3
Output: 4
Explanation: [
[1, 2, 3],
[1, 3, 2],
[2, 1, 3],
[3, 2, 1]
]
We start from [1, 2, 3], which is a swap permutation
because we applied 0 swap operations, and we apply
one of the following swaps:
[1, 2, 3] => [1, 3, 2]
[1, 2, 3] => [2, 1, 3]
[1, 2, 3] => [3, 2, 1]
Notice that we can only apply one swap operation
because we are left with only 1 item that is not swapped.
For larger values of N we can have multiple chained operations.
Notes:
3 <= N <= 12
Walkthroughs of the solution. Try the steps first, then watch to compare approaches.
Free plan: 30 tutor messages. Premium is unlimited.
Saved
Ctrl + Enter to check