Permutations III - Problem
Alternating Permutations Challenge

Given an integer n, you need to find all alternating permutations of the first n positive integers. An alternating permutation is a special arrangement where no two adjacent elements have the same parity - meaning you can't have two odd numbers or two even numbers next to each other.

For example, [1, 2, 3, 4] is alternating because: 1 (odd) → 2 (even) → 3 (odd) → 4 (even). But [1, 3, 2, 4] is not alternating because 1 and 3 are both odd and adjacent.

Goal: Return all valid alternating permutations sorted in lexicographical order.

Input & Output

example_1.py — Basic Case
$ Input: n = 3
Output: [[1, 2, 3], [3, 2, 1]]
💡 Note: For n=3, we have numbers [1,2,3]. Only two arrangements alternate: [1,2,3] (odd→even→odd) and [3,2,1] (odd→even→odd). Other arrangements like [1,3,2] fail because 1 and 3 are both odd.
example_2.py — Larger Case
$ Input: n = 4
Output: [[1, 2, 3, 4], [1, 4, 3, 2], [2, 1, 4, 3], [2, 3, 4, 1], [3, 2, 1, 4], [3, 4, 1, 2]]
💡 Note: With n=4, we have more possibilities. Each valid permutation alternates between odd and even numbers. For example, [1,2,3,4] goes odd→even→odd→even, which satisfies the constraint.
example_3.py — Edge Case
$ Input: n = 1
Output: [[1]]
💡 Note: With only one number, there are no adjacent elements to check, so [1] is trivially an alternating permutation.

Constraints

  • 1 ≤ n ≤ 8
  • The result must be sorted in lexicographical order
  • Each permutation contains integers from 1 to n exactly once

Visualization

Tap to expand
The Alternating Dance: Building Valid PermutationsStep 1: Choose First DancerAny number 1 to n can start (no constraint yet)1Tall (odd)2Short (even)3Tall (odd)4Short (even)Step 2: Smart Choice for Second PositionIf first is odd (like 1), second must be even (2 or 4)If first is even (like 2), second must be odd (1 or 3)✓ Valid✗ InvalidResult: Efficient GenerationOnly build valid permutations, skip impossible combinationsMuch faster than generating all n! permutations
Understanding the Visualization
1
Start Fresh
Begin with empty arrangement and all dancers available
2
Choose Wisely
At each position, only consider dancers that won't break the alternating rule
3
Build Gradually
Place one dancer at a time, checking parity with the previous dancer
4
Backtrack Smart
If we hit a dead end, backtrack and try a different dancer
5
Collect Results
When we place all dancers successfully, we found a valid arrangement
Key Takeaway
🎯 Key Insight: Use backtracking with parity checking to build only valid alternating permutations, avoiding the exponential waste of generating and filtering all permutations.
Asked in
Google 15 Amazon 12 Meta 8 Microsoft 6
24.0K Views
Medium Frequency
~15 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