Permutations III - Problem
Given an integer n, 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 all such alternating permutations sorted in lexicographical order.
For example, if n = 4, the integers are [1, 2, 3, 4]. A valid alternating permutation would be [1, 2, 3, 4] since adjacent pairs (1,2), (2,3), and (3,4) alternate between odd and even.
Input & Output
Example 1 — Basic Case
$
Input:
n = 4
›
Output:
[[1,2,3,4],[2,1,4,3],[2,3,4,1],[3,2,1,4],[3,4,1,2],[4,1,2,3],[4,3,2,1]]
💡 Note:
For n=4, we need permutations of [1,2,3,4] where no adjacent elements have the same parity. Valid permutations alternate between odd and even numbers.
Example 2 — Small Case
$
Input:
n = 3
›
Output:
[[1,2,3],[3,2,1]]
💡 Note:
For n=3 with numbers [1,2,3]: [1,2,3] works (odd-even-odd), and [3,2,1] works (odd-even-odd). [2,3,1] doesn't work because 3 and 1 are both odd.
Example 3 — Edge Case
$
Input:
n = 1
›
Output:
[[1]]
💡 Note:
Single element always forms valid alternating permutation since there are no adjacent pairs to violate constraint
Constraints
- 0 ≤ n ≤ 8
- Result must be sorted in lexicographical order
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code