Practice/Meta/Leetcode 2164. Sort Even and Odd Indices Independently
Leetcode 2164. Sort Even and Odd Indices Independently
CodingOptional
Problem
You are given a 0-indexed integer array nums. Your task is to rearrange the array using the following process:
- Extract all elements at even indices (0, 2, 4, ...) and sort them in ascending order
- Extract all elements at odd indices (1, 3, 5, ...) and sort them in descending order
- Place the sorted even-indexed elements back into the even positions
- Place the sorted odd-indexed elements back into the odd positions
Return the rearranged array.
Requirements
- Elements at even indices must be sorted in non-decreasing (ascending) order
- Elements at odd indices must be sorted in non-increasing (descending) order
- The original index parity (even/odd) of each position must be preserved
- Modify the array according to the sorting rules and return the result
Constraints
1 <= nums.length <= 100
1 <= nums[i] <= 100
- The array length can be either even or odd
Examples
Example 1:
`
Input: nums = [4, 1, 2, 3]
Output: [2, 3, 4, 1]
Explanation:
- Even indices (0, 2): values [4, 2] → sorted ascending → [2, 4]
- Odd indices (1, 3): values [1, 3] → sorted descending → [3, 1]
- Reconstructed: [2, 3, 4, 1]
`
Example 2:
`
Input: nums = [2, 1]
Output: [2, 1]
Explanation:
- Even indices (0): values [2] → already sorted
- Odd indices (1): values [1] → already sorted
- Result: [2, 1]
`
Example 3:
`
Input: nums = [5, 4, 3, 4, 5, 2, 1, 6]
Output: [1, 6, 3, 4, 5, 4, 5, 2]
Explanation:
- Even indices: [5, 3, 5, 1] → [1, 3, 5, 5]
- Odd indices: [4, 4, 2, 6] → [6, 4, 4, 2]
- Merged back: [1, 6, 3, 4, 5, 4, 5, 2]
`