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
INPUTALGORITHMRESULTn = 4, k = 21234oddevenoddevenFind 2nd alternatingpermutation where noadjacent elements havesame parity1Separate Groups2Calculate Patterns3Direct ConstructionOdd: [1,3], Even: [2,4]Pattern O-E-O-E: 2!×2!=4Pattern E-O-E-O: 2!×2!=4k=2 --> 2nd in first pattern[1,2,4,3]✓ Alternating pattern:1(odd) → 2(even)2(even) → 4(even)4(even) → 3(odd)Valid alternatingpermutation found!Key Insight:Mathematical construction avoids generating invalid permutations by using combinatorial propertiesTutorialsPoint - Permutations IV | Mathematical Construction
Asked in
Google 25 Microsoft 18 Amazon 15 Apple 12
23.4K Views
Medium Frequency
~35 min Avg. Time
856 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