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
Sort Even and Odd Indices Independently INPUT nums = [4, 1, 2, 3] idx 0 idx 1 idx 2 idx 3 4 1 2 3 Even indices (0, 2) Odd indices (1, 3) Separated Values: Even: [4, 2] Odd: [1, 3] ALGORITHM STEPS 1 Extract Values Separate even/odd indices 2 Sort Even (Ascending) [4, 2] --> [2, 4] 3 Sort Odd (Descending) [1, 3] --> [3, 1] 4 Merge Back Interleave sorted values 2 3 4 1 Time: O(n log n) | Space: O(n) FINAL RESULT Output: [2, 3, 4, 1] idx 0 idx 1 idx 2 idx 3 2 3 4 1 Verification: Even indices: 2, 4 (sorted ascending - OK) Odd indices: 3, 1 (sorted descending - OK) SUCCESS Key Insight: The in-place sorting approach separates values by index parity, sorts each group independently (even indices ascending, odd indices descending), then merges them back by placing sorted values at their original positions alternately. TutorialsPoint - Sort Even and Odd Indices Independently | In-Place Sorting Approach
Asked in
Microsoft 15 Google 12
8.5K Views
Medium Frequency
~15 min Avg. Time
234 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