LeetCode 2164: Sort Even and Odd Indices Independently Solution

Master LeetCode problem 2164 (Sort Even and Odd Indices Independently), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

2164. Sort Even and Odd Indices Independently

Problem Explanation

Explanation

To solve this problem, we can follow these steps:

  1. Separate the elements at even indices and odd indices.
  2. Sort the elements at even indices in non-decreasing order.
  3. Sort the elements at odd indices in non-increasing order.
  4. Merge the sorted even indices array with the sorted odd indices array to form the final result.

Time complexity: O(n log n) where n is the number of elements in the input array. Space complexity: O(n) for storing even and odd indices arrays.

Solution Code

import java.util.Arrays;

class Solution {
    public int[] sortArrayByParityII(int[] nums) {
        int n = nums.length;
        int[] even = new int[n / 2];
        int[] odd = new int[n / 2];
        
        int evenIdx = 0, oddIdx = 0;
        for (int i = 0; i < n; i++) {
            if (i % 2 == 0) {
                even[evenIdx++] = nums[i];
            } else {
                odd[oddIdx++] = nums[i];
            }
        }
        
        Arrays.sort(even);
        Arrays.sort(odd);
        
        int[] result = new int[n];
        evenIdx = 0; oddIdx = odd.length - 1;
        for (int i = 0; i < n; i++) {
            if (i % 2 == 0) {
                result[i] = even[evenIdx++];
            } else {
                result[i] = odd[oddIdx--];
            }
        }
        
        return result;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 2164 (Sort Even and Odd Indices Independently)?

This page provides optimized solutions for LeetCode problem 2164 (Sort Even and Odd Indices Independently) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 2164 (Sort Even and Odd Indices Independently)?

The time complexity for LeetCode 2164 (Sort Even and Odd Indices Independently) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 2164 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2164 in Java, C++, or Python.

Back to LeetCode Solutions