Leetcode 2164: Sort Even and Odd Indices Independently

grid47
grid47
Exploring patterns and algorithms
Apr 4, 2024 5 min read

You are given a 0-indexed integer array ’nums’. Your task is to rearrange the elements of ’nums’ by sorting the values at odd indices in non-increasing order and the values at even indices in non-decreasing order. Return the rearranged array.
Problem
Approach
Steps
Complexity
Input: The input consists of an integer array 'nums'.
Example: nums = [5, 2, 8, 1]
Constraints:
• 1 <= nums.length <= 100
• 1 <= nums[i] <= 100
Output: The output should be the array 'nums' after rearranging it according to the given sorting rules.
Example: [2, 8, 5, 1]
Constraints:
• The output must preserve the rearrangement order for odd and even indices as described.
Goal: Sort elements at odd indices in non-increasing order and elements at even indices in non-decreasing order.
Steps:
• Iterate through the array and sort the elements at even indices in non-decreasing order.
• Iterate through the array and sort the elements at odd indices in non-increasing order.
Goal: The input array nums has between 1 and 100 elements, and each element is between 1 and 100.
Steps:
• nums.length between 1 and 100
• 1 <= nums[i] <= 100
Assumptions:
• The input array will always contain between 1 and 100 elements.
• Elements are integers in the range 1 to 100.
Input: Example 1: nums = [5, 2, 8, 1]
Explanation: First, the elements at odd indices [2, 1] are sorted in non-increasing order to become [8, 1]. Then, the elements at even indices [5, 8] are sorted in non-decreasing order to become [2, 5]. The final array is [2, 8, 5, 1].

Input: Example 2: nums = [9, 7]
Explanation: There is only one element at an odd index and one at an even index, so the array remains [7, 9].

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus