easy +10 pts

Rearrange Positives and Negatives

Partition a list in-place so that all negative numbers appear before non-negative numbers.

Write a function `rearrange_pos_neg(nums)` that takes a list of integers `nums` and rearranges the elements in-place so that all negative numbers appear before all non-negative numbers (zero and positive). The relative order of elements within the negative group and within the non-negative group does not matter. The function should modify the original list in-place; the returned value is ignored. The solution must run in O(n) time and use O(1) extra space.

Constraints

0 <= len(nums) <= 10^5, -10^9 <= nums[i] <= 10^9. Time O(n), Space O(1).

Example

>>> nums = [1, -2, 3, -4, 5]
>>> rearrange_pos_neg(nums)
>>> nums
[-2, -4, 3, 1, 5]  # any order with negatives first is accepted

>>> nums = []
>>> rearrange_pos_neg(nums)
>>> nums
[]

>>> nums = [-1, 0, 2]
>>> rearrange_pos_neg(nums)
>>> nums
[-1, 0, 2]
10 points ~15 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Use two pointers: one scanning left to right, one scanning right to left.
Find a non-negative on the left and a negative on the right, then swap them.
Remember zero is non-negative.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.