Permutations III - Problem
Alternating Permutations Challenge
Given an integer
For example,
Goal: Return all valid alternating permutations sorted in lexicographical order.
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
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.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code