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
Alternating Permutations: n=4Input Numbers:1234ODDEVENODDEVENValid Alternating Permutations:[1,2,3,4] ✓[2,1,4,3] ✓[2,3,4,1] ✓[3,2,1,4] ✓O-E-O-EE-O-E-OE-O-E-OO-E-O-EInvalid Example:[1,3,2,4] ✗O-O (adjacent odds)Total: 7 valid permutations
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
Asked in
Google 35 Microsoft 28 Amazon 22
23.5K Views
Medium Frequency
~25 min Avg. Time
890 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