Leetcode Problem 2149. Rearrange Array Elements by Sign

2149. Rearrange Array Elements by Sign

Leetcode Solutions

Two-Pointer Approach

  1. Initialize two empty lists, positives and negatives, to store the positive and negative numbers separately.
  2. Iterate through the nums array and append each number to the positives list if it is positive, or to the negatives list if it is negative.
  3. Initialize a new list result to store the rearranged array.
  4. Use two index variables, posIndex and negIndex, starting at 0, to keep track of the current index in the positives and negatives lists.
  5. Loop through the range from 0 to the length of nums, incrementing by 2 each time.
  6. On each iteration, set result[i] to positives[posIndex] and increment posIndex by 1.
  7. Set result[i + 1] to negatives[negIndex] and increment negIndex by 1.
  8. Return the result list.
UML Thumbnail

In-Place Two-Pointer Approach

Ask Question

Programming Language
image/screenshot of info(optional)
Full Screen
Loading...

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...