LeetCode 2149: Rearrange Array Elements by Sign Solution

Master LeetCode problem 2149 (Rearrange Array Elements by Sign), a medium 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.

2149. Rearrange Array Elements by Sign

Problem Explanation

Explanation

To rearrange the array elements by sign, we can follow these steps:

  1. Separate the positive and negative integers into two separate lists.
  2. Sort both lists in descending order of absolute values.
  3. Merge the two lists alternately starting with a positive integer.

Time Complexity: O(nlogn) where n is the length of the input array nums. Space Complexity: O(n) where n is the length of the input array nums.

Solution Code

import java.util.*;

class Solution {
    public int[] rearrangeArrayBySign(int[] nums) {
        List<Integer> positive = new ArrayList<>();
        List<Integer> negative = new ArrayList<>();
        
        for (int num : nums) {
            if (num > 0) {
                positive.add(num);
            } else {
                negative.add(num);
            }
        }
        
        Collections.sort(positive, Collections.reverseOrder());
        Collections.sort(negative, Collections.reverseOrder());
        
        int[] result = new int[nums.length];
        int i = 0, j = 0;
        
        for (int k = 0; k < nums.length; k++) {
            if (k % 2 == 0) {
                result[k] = positive.get(i++);
            } else {
                result[k] = negative.get(j++);
            }
        }
        
        return result;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 2149 (Rearrange Array Elements by Sign)?

This page provides optimized solutions for LeetCode problem 2149 (Rearrange Array Elements by Sign) 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 2149 (Rearrange Array Elements by Sign)?

The time complexity for LeetCode 2149 (Rearrange Array Elements by Sign) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 2149 on DevExCode?

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

Back to LeetCode Solutions