Permutations IV - Problem
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.
An alternating permutation alternates between odd and even numbers at adjacent positions. For example, [1,2,3,4] is alternating because 1(odd), 2(even), 3(odd), 4(even) alternate.
Input & Output
Example 1 — Basic Case
$
Input:
n = 4, k = 2
›
Output:
[1,2,4,3]
💡 Note:
For n=4, alternating permutations start with odd or even. The valid permutations in lexicographical order are [1,2,3,4], [1,2,4,3], [1,4,3,2], etc. The 2nd one is [1,2,4,3].
Example 2 — First Permutation
$
Input:
n = 3, k = 1
›
Output:
[1,2,3]
💡 Note:
For n=3, we have odd=[1,3] and even=[2]. Only pattern O-E-O is valid. The lexicographically first alternating permutation is [1,2,3].
Example 3 — Invalid k
$
Input:
n = 2, k = 5
›
Output:
[]
💡 Note:
For n=2, we have [1,2] and [2,1] as the only alternating permutations. Since k=5 > 2 total permutations, return empty list.
Constraints
- 1 ≤ n ≤ 15
- 1 ≤ k ≤ 106
- If fewer than k alternating permutations exist, return empty list
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code