Skip to content

Latest commit

 

History

History
46 lines (30 loc) · 702 Bytes

File metadata and controls

46 lines (30 loc) · 702 Bytes

Rearrange Array Elements by Sign

Problem Link

https://leetcode.com/problems/rearrange-array-elements-by-sign/


Pattern

  • Two Pointer
  • In-place

Approach

Use two pointers to place positive and negative elements alternately or collect and rebuild.


Time Complexity

O(n)

Space Complexity

O(1) or O(n) depending on method


Java Solution (one approach)

class Solution {
    public int[] rearrangeArray(int[] nums) {
        int[] res = new int[nums.length];
        int pos = 0, neg = 1;
        for (int n : nums) {
            if (n > 0) { res[pos] = n; pos += 2; }
            else { res[neg] = n; neg += 2; }
        }
        return res;
    }
}