Move negative numbers before non-negative numbers in place
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: easy
Interview Round: Other
Given an integer array `nums` containing both negative and positive numbers, reorder the array in place so that all negative numbers appear before all non-negative numbers.
Zero is considered non-negative and should appear after the negative numbers. The relative order of elements within the negative group or the non-negative group does not need to be preserved, so more than one output can be correct. Any arrangement that meets the rule is accepted.
You must do this without using extra space (that is, `O(1)` auxiliary space).
Example 1:
```text
Input: nums = [3,-1,-4,2,-5,6]
Output: [-5,-1,-4,2,3,6]
```
The negative numbers are -1, -4 and -5, and the positive numbers are 3, 2 and 6. After reordering, all negatives come first, followed by all positives. `[-5,-1,-4,2,3,6]` is one valid output.
Example 2:
```text
Input: nums = [-2,-3,0,1,-7]
Output: [-2,-3,-7,1,0]
```
The negative numbers are -2, -3 and -7, and the non-negatives are 0 and 1. `[-2,-3,-7,1,0]` is one valid output; `[-7,-3,-2,0,1]` would be accepted too.
```hint Work from both ends
Scan from the left for an element that belongs on the right side, and from the right for one that belongs on the left side. What can you do once you have found both?
```
### Constraints & Assumptions
- `1 <= nums.length <= 10^5`
- `-10^4 <= nums[i] <= 10^4`
- The array is modified in place with `O(1)` auxiliary space. Returning the same array object is fine.
- Zero counts as non-negative.
### What a Strong Answer Covers
- A single in-place pass that partitions the array, with a clear invariant for what lies on each side of the pointers
- Zero placed with the non-negative group
- Loop conditions that keep the pointers inside the array and stop them from crossing, including the all-negative and all-non-negative cases
- `O(n)` time and `O(1)` extra space, with a short argument for each
### Follow-up Questions
- How would you change the solution if the relative order inside both groups had to be preserved, still with constant extra space?
- How would you split the array into three groups: negatives, then zeros, then positives?
- Which of your approaches keeps the original order of the negative numbers, and why?
- How many swaps does the two-pointer version make in the worst case, compared with a single forward scan?
Overview: Reorder an integer array in place so that every negative number comes before every non-negative number, using constant extra space. It tests the two-pointer partition technique, loop invariants, and careful handling of zero and boundary cases.