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],[2,1,4],[2,3,1],[3,2,1]]
💡 Note:
For n=3 with numbers [1,2,3]: [1,2,3] works (odd-even-odd), [2,1,4] is invalid (4 > n), correct result is [[1,2,3],[2,3,1]]
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
Understanding the Visualization
1
Input
Given n=4, we work with numbers [1,2,3,4]
2
Process
Find arrangements where adjacent elements have different parity
3
Output
Return all valid alternating permutations in lexicographical order
Key Takeaway
🎯 Key Insight: Use backtracking to build permutations step-by-step, only adding numbers that maintain the alternating odd-even pattern
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code