Permutations IV Problem
Description
LeetCode Problem 3470.
Given two integers, n and k, an alternating permutation is a permutation of the first n positive integers such that no two adjacent elements are both odd or both even.
Return the k-th alternating permutation sorted in lexicographical order. If there are fewer than k valid alternating permutations, return an empty list.
Example 1:
Input: n = 4, k = 6
Output: [3,4,1,2]
Explanation:
The lexicographically-sorted alternating permutations of [1, 2, 3, 4] are:
1. [1, 2, 3, 4]
2. [1, 4, 3, 2]
3. [2, 1, 4, 3]
4. [2, 3, 4, 1]
5. [3, 2, 1, 4]
6. [3, 4, 1, 2] ← 6th permutation
7. [4, 1, 2, 3]
8. [4, 3, 2, 1]
Since k = 6, we return [3, 4, 1, 2].
Example 2:
Input: n = 3, k = 2
Output: [3,2,1]
Explanation:
The lexicographically-sorted alternating permutations of [1, 2, 3] are:
1. [1, 2, 3]
2. [3, 2, 1] ← 2nd permutation
Since k = 2, we return [3, 2, 1].
Example 3:
Input: n = 2, k = 3
Output: []
Explanation:
The lexicographically-sorted alternating permutations of [1, 2] are:
1. [1, 2]
2. [2, 1]
There are only 2 alternating permutations, but k = 3, which is out of range. Thus, we return an empty list [].
Constraints:
1 <= n <= 1001 <= k <= 10^15
Solution
Approach: Counting and Building Digit by Digit
An alternating permutation alternates between odd and even numbers. Once a prefix is fixed, the remaining numbers must still alternate, which is only possible if the counts of odd and even numbers left differ by at most one and fit the parity the next position needs. When it is possible, the odd numbers can be arranged in o! ways and the even ones in e! ways, so the number of completions is o! * e!; otherwise it is 0.
Build the answer position by position. For each position try the unused numbers in increasing order (skipping those with the same parity as the previous element), count the completions after choosing the number, and subtract that count from k if k is larger; otherwise take that number and move on. If no number can be chosen at some position, fewer than k permutations exist and the answer is empty.
Factorials grow huge, so they are capped at a value above 10^15.
Complexity: O(n^2) time, O(n) space.
class Solution:
def permute(self, n: int, k: int) -> List[int]:
cap = 2 * 10**15
fact = [1] * (n + 1)
for i in range(1, n + 1):
fact[i] = min(cap, fact[i - 1] * i)
def ways(o: int, e: int, odd_next: bool) -> int:
if o + e == 0:
return 1
ok = (o == e or o == e + 1) if odd_next else (e == o or e == o + 1)
return min(cap, fact[o] * fact[e]) if ok else 0
used = [False] * (n + 1)
odd, even = (n + 1) // 2, n // 2
ans = []
for pos in range(n):
chosen = False
for v in range(1, n + 1):
if used[v] or (ans and (v - ans[-1]) % 2 == 0):
continue
o, e = odd - (v % 2), even - (1 - v % 2)
cnt = ways(o, e, v % 2 == 0)
if k > cnt:
k -= cnt
continue
used[v] = True
ans.append(v)
odd, even = o, e
chosen = True
break
if not chosen:
return []
return ans