February-Leetcode-POTD- 14: 2149. Rearrange Array Elements by Sign

Shubham Saha
2 min readFeb 16, 2024

--

QUESTION -> Rearrange Array Elements by Sign

Problem Statement:

We have a 0-indexed integer array nums of even length consisting of an equal number of positive and negative integers.

we have to rearrange the elements of nums such that the modified array follows the given conditions:

  1. Every consecutive pair of integers have opposite signs.
  2. For all integers with the same sign, the order in which they were present in nums is preserved.
  3. The rearranged array begins with a positive integer.

Intuition :

i ) 1st observation as the array is begin with positive integer, so according to condition first , we get that in even indexes there is always a positive integers.

ii ) If we try to rearrange the array in place, i think this is not possible because as per condition second we have to maintain the order.

iii ) We are taking a extra array of size n, to solve this in order to maintain the order.

APPROACH:

  1. We will iterate over the nums vector.
  2. So we directly putting values in the result vector with the help of 2 pointer approach where initially both the indexes evenIdx and oddIdx 0 and 1.
  3. If we encounter positive element then will put values in the result vector with the help of result[evenIdx] = nums[i] and if found negative element then result[oddIdx] = nums[i].

Complexity:

  • Time complexity: O(n)
  • Space complexity: O(n)

CODE :

Note : Hi reader’s , I’m just trying to share my approaches. Due to time constraint i’m not be able to briefly explain my approaches in some posts , so please bear me for this. If you have any suggestions please let me know.

HOPE YOU LIKE MY APPROACH!!!

Thank you For Reading!!!

Shubham Saha

--

--

Shubham Saha
Shubham Saha

Written by Shubham Saha

Full Stack Developer | Expert in React, Node.js, Express.js, MongoDB, MySQL | Proficient in Data Structures and Algorithms | Exploring Next.js

No responses yet