Sort Even and Odd Indices Independently — LeetCode 2164 Python Solution

EasyArraySorting
Problem
#2164
Pattern
Sorting
Reading time
2 min

The problem

You are given a 0-indexed integer array nums. Rearrange the values of nums according to the following rules: Sort the values at odd indices of nums in non-increasing order.

Example

Input
nums = [4,1,2,3]
Output
[2,3,4,1]
Explanation
First, we sort the values present at odd indices (1 and 3) in non-increasing order.

Python solution

Python
class Solution:
    def sortEvenOdd(self, nums: List[int]) -> List[int]:
        a = sorted(nums[::2])
        b = sorted(nums[1::2], reverse=True)
        nums[::2] = a
        nums[1::2] = b
        return nums

Complexity

MeasureComplexity
TimeO(n \log n)
SpaceO(n) auxiliary

Pattern: Sorting

Spend O(n log n) once to buy an ordering that makes the rest of the problem trivial. LeetCode 2164. Sort Even and Odd Indices Independently is filed here because LeetCode tags it Sorting, which is the vocabulary this hub collects.

The sorting guide has the Python template for the pattern and the 401 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2164. Sort Even and Odd Indices Independently?
LeetCode 2164. Sort Even and Odd Indices Independently is rated Easy on LeetCode.
What is the time complexity of LeetCode 2164. Sort Even and Odd Indices Independently?
The Python solution on this page runs in O(n \log n).
What is the space complexity of LeetCode 2164. Sort Even and Odd Indices Independently?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 2164. Sort Even and Odd Indices Independently cover?
LeetCode 2164. Sort Even and Odd Indices Independently is tagged Array and Sorting on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview