Permutations IV - Problem

An alternating permutation is a fascinating mathematical concept where adjacent elements follow a strict pattern of alternating between odd and even numbers. Given two integers n and k, you need to find the k-th alternating permutation of the first n positive integers when all valid alternating permutations are sorted in lexicographical order.

In an alternating permutation, no two adjacent elements can both be odd or both be even. For example, [1, 2, 3, 4] is alternating because 1(odd) → 2(even) → 3(odd) → 4(even), but [1, 3, 2, 4] is not because 1(odd) → 3(odd).

Goal: Return the k-th alternating permutation in lexicographical order, or an empty list if fewer than k valid permutations exist.

Input & Output

example_1.py — Basic Alternating Pattern
$ Input: n = 4, k = 1
Output: [1, 2, 3, 4]
💡 Note: With n=4, we have numbers [1,2,3,4]. The first alternating permutation in lexicographical order is [1,2,3,4] because 1(odd)→2(even)→3(odd)→4(even) alternates perfectly.
example_2.py — Middle Permutation
$ Input: n = 4, k = 3
Output: [1, 4, 3, 2]
💡 Note: The valid alternating permutations in order are: [1,2,3,4], [1,4,3,2], [2,1,4,3], [2,3,4,1], [3,2,1,4], [3,4,1,2], [4,1,2,3], [4,3,2,1]. The 3rd one is [1,4,3,2].
example_3.py — No Valid Permutation
$ Input: n = 3, k = 10
Output: []
💡 Note: With n=3, we have [1,2,3] where 1,3 are odd and 2 is even. Valid alternating permutations are: [1,2,3], [3,2,1]. Since k=10 > 2, we return an empty list.

Time & Space Complexity

Time Complexity
⏱️
O(n²)

For each position (n), we may need to scan remaining numbers (O(n))

n
2n
Quadratic Growth
Space Complexity
O(n)

Store result array and lists of remaining odd/even numbers

n
2n
Linearithmic Space

Constraints

  • 1 ≤ n ≤ 10
  • 1 ≤ k ≤ 106
  • Numbers are the first n positive integers: [1, 2, 3, ..., n]
  • Adjacent elements in alternating permutation cannot have same parity
Asked in
25.0K Views
Medium Frequency
~15 min Avg. Time
850 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen