Sort Even and Odd Indices Independently - Problem

You're given a 0-indexed integer array nums and need to rearrange its values following two independent sorting rules:

  • Even indices (0, 2, 4, ...): Sort values in non-decreasing order (ascending)
  • Odd indices (1, 3, 5, ...): Sort values in non-increasing order (descending)

Example walkthrough:
Given nums = [4,1,2,3]
• Even indices: positions 0,2 have values [4,2] → sort ascending → [2,4]
• Odd indices: positions 1,3 have values [1,3] → sort descending → [3,1]
• Result: [2,3,4,1]

The key insight is that we're not sorting the entire array - we're treating even and odd positioned elements as two separate groups with different sorting rules!

Input & Output

example_1.py — Basic Case
$ Input: nums = [4,1,2,3]
Output: [2,3,4,1]
💡 Note: Even indices (0,2) have values [4,2]. Sorted ascending: [2,4]. Odd indices (1,3) have values [1,3]. Sorted descending: [3,1]. Result: [2,3,4,1].
example_2.py — Already Sorted Case
$ Input: nums = [2,1]
Output: [2,1]
💡 Note: Even index 0 has value [2] (already sorted). Odd index 1 has value [1] (already sorted). No changes needed.
example_3.py — Larger Array
$ Input: nums = [1,9,2,8,3,7,4,6,5]
Output: [1,9,2,8,3,7,4,6,5]
💡 Note: Even indices (0,2,4,6,8) have values [1,2,3,4,5] - already sorted ascending. Odd indices (1,3,5,7) have values [9,8,7,6] - already sorted descending. Array remains unchanged.

Constraints

  • 1 ≤ nums.length ≤ 100
  • 1 ≤ nums[i] ≤ 100
  • nums.length can be odd or even
  • All elements are positive integers

Visualization

Tap to expand
Theater Seating: Sort Even and Odd IndicesInitial Seating (Heights: 4,1,2,3)Seat 0(Even)H:4Seat 1(Odd)H:1Seat 2(Even)H:2Seat 3(Odd)H:3Step 1: Separate by Seat TypeEven SeatsHeights: [4, 2]Sort: AscendingOdd SeatsHeights: [1, 3]Sort: DescendingStep 2: Sort Each GroupEven SortedHeights: [2, 4]Shortest → TallestOdd SortedHeights: [3, 1]Tallest → ShortestStep 3: Final Seating ArrangementSeat 0(Even)H:2Seat 1(Odd)H:3Seat 2(Even)H:4Seat 3(Odd)H:1Result: [2, 3, 4, 1]
Understanding the Visualization
1
Separate Groups
Collect all people from even-numbered seats and odd-numbered seats separately
2
Sort Each Group
Sort even-seat people by height ascending, odd-seat people by height descending
3
Seat Assignment
Place sorted people back into their respective even/odd seats
4
Final Arrangement
Everyone is now properly arranged according to their seat group's rules
Key Takeaway
🎯 Key Insight: Transform one complex sorting problem into two simple, independent sorting operations by separating elements based on index parity!
Asked in
Google 25 Amazon 20 Meta 15 Microsoft 18
28.4K Views
Medium Frequency
~15 min Avg. Time
850 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