#2164

Sort Even and Odd Indices Independently

Easy
ArraySortingArraySorting
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log n)
Space
O(n)
O(n)
💡

Intuition

Time O(n log n)Space O(n)

The optimal solution directly sorts the even and odd indexed elements in a single pass through the array, which is more efficient. By using two separate lists and sorting them independently, we achieve the desired result without unnecessary complexity.

⚙️

Algorithm

4 steps
  1. 1Step 1: Initialize two empty lists for even and odd indexed elements.
  2. 2Step 2: Iterate through the original array and populate the even and odd lists based on the index.
  3. 3Step 3: Sort the even list in non-decreasing order and the odd list in non-increasing order.
  4. 4Step 4: Create a new result array and fill it by alternating between the sorted even and odd lists.
solution.py13 lines
1def sortEvenOdd(nums):
2    even = sorted(nums[i] for i in range(0, len(nums), 2))
3    odd = sorted((nums[i] for i in range(1, len(nums), 2)), reverse=True)
4    result = []
5    even_index, odd_index = 0, 0
6    for i in range(len(nums)):
7        if i % 2 == 0:
8            result.append(even[even_index])
9            even_index += 1
10        else:
11            result.append(odd[odd_index])
12            odd_index += 1
13    return result

Complexity note: The time complexity is O(n log n) due to the sorting of the even and odd lists. The space complexity is O(n) because we are using additional space to store the sorted lists.

  • 1Elements at even and odd indices can be treated independently.
  • 2Sorting can be performed separately for both groups.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.