Sort Even and Odd Indices Independently - Problem
You are given a 0-indexed integer array nums. Rearrange the values of nums according to the following rules:
1. Sort the values at odd indices of nums in non-increasing order.
For example, if nums = [4,1,2,3] before this step, it becomes [4,3,2,1] after. The values at odd indices 1 and 3 are sorted in non-increasing order.
2. Sort the values at even indices of nums in non-decreasing order.
For example, if nums = [4,1,2,3] before this step, it becomes [2,1,4,3] after. The values at even indices 0 and 2 are sorted in non-decreasing order.
Return the array formed after rearranging the values of nums.
Input & Output
Example 1 — Basic Case
$
Input:
nums = [4,1,2,3]
›
Output:
[2,3,4,1]
💡 Note:
Even indices (0,2): [4,2] → sorted ascending: [2,4]. Odd indices (1,3): [1,3] → sorted descending: [3,1]. Result: [2,3,4,1]
Example 2 — Single Element Groups
$
Input:
nums = [2,1]
›
Output:
[2,1]
💡 Note:
Even indices (0): [2] → stays [2]. Odd indices (1): [1] → stays [1]. Result: [2,1]
Example 3 — Larger Array
$
Input:
nums = [4,1,2,3,1,2,3,1]
›
Output:
[1,3,2,3,3,1,4,1]
💡 Note:
Even indices (0,2,4,6): [4,2,1,3] → sorted ascending: [1,2,3,4]. Odd indices (1,3,5,7): [1,3,2,1] → sorted descending: [3,3,1,1]. Result: [1,3,2,3,3,1,4,1]
Constraints
- 1 ≤ nums.length ≤ 100
- -100 ≤ nums[i] ≤ 100
Visualization
Tap to expand
Understanding the Visualization
1
Input Array
Original array with mixed values at even and odd indices
2
Separate by Index
Group values by even indices (ascending) and odd indices (descending)
3
Final Result
Reassembled array with sorted values at their respective index types
Key Takeaway
🎯 Key Insight: Separate elements by index parity, sort each group with different orders, then reassemble
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code