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
Permutations III - Alternating Permutation INPUT n = 4 Generate permutations of [1,2,3,4] 1 ODD 2 EVEN 3 ODD 4 EVEN CONSTRAINT Adjacent elements must alternate: ODD-EVEN-ODD-EVEN or EVEN-ODD-EVEN-ODD Valid: [1,2,3,4] O-E-O-E pattern Invalid: [1,3,2,4] O-O adjacent! ALGORITHM STEPS 1 Backtracking Setup Track used numbers, build path 2 Check Parity curr % 2 != prev % 2 3 Try Each Number 1 to n, skip if invalid 4 Collect Results When path.length == n Decision Tree (partial) [] 1 2 3 2 1 3 2 FINAL RESULT 7 valid alternating permutations: [1, 2, 3, 4] O-E-O-E [2, 1, 4, 3] E-O-E-O [2, 3, 4, 1] E-O-E-O [3, 2, 1, 4] O-E-O-E [3, 4, 1, 2] O-E-O-E [4, 1, 2, 3] E-O-E-O [4, 3, 2, 1] E-O-E-O OK - Sorted! Lexicographical order Key Insight: Use backtracking with parity check: at each position, only try numbers whose parity differs from the previous. Prune invalid branches early. Time: O(n! * n), Space: O(n) for recursion. Generates results in lex order naturally. TutorialsPoint - Permutations III | Optimal Backtracking Solution
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