Skip to main content
1:1 mock interviews with Sumit, scored on a real hiring rubric.Book a slot →

Move All Negative Elements to One Side of an Array: Two Pointer Partition

Move all negative numbers to the left side of an array in one pass and O(1) space. Two pointer partition explained with an animated dry run and code in Java, C, C++, JavaScript and Python.

Sumit KumarUpdated Oct 8, 20266 min readDSA
Move All Negative Elements to One Side of an Array: Two Pointer Partition

"Move all negative elements to one side of the array" is a classic partitioning problem. It is the same idea that powers Quicksort and the Dutch National Flag algorithm, applied to just two groups: negatives and non-negatives. In this post you will learn how to think about it, compare approaches, watch the two pointer solution animated, and get tested code in Java, C, C++, JavaScript and Python.

Problem statement#

Given an array arr of positive and negative integers, rearrange it in place so that all negative numbers come before all non-negative numbers. The order of elements within each group does not matter.

Text
Input:  [-12, 11, -13, -5, 6, -7, 5, -3, -6]
Output: [-12, -6, -13, -5, -3, -7, 5, 6, 11]

Input:  [1, -1, 3, 2, -7, -5, 11, 6]
Output: [-5, -1, -7, 2, 3, 1, 11, 6]   (any order inside each group is fine)

How to think about this problem#

We are not sorting. We only need to split the array into two groups. Think of it like this:

  • The left side of the array should end up holding negatives.
  • The right side should end up holding non-negatives.

So scan from both ends at once. From the left, skip elements that are already negative (they are fine where they are) and stop at the first positive one, which is in the wrong place. From the right, skip elements that are already non-negative and stop at the first negative one, also in the wrong place. Now you have two misplaced elements. Swap them, and both are fixed with a single swap.

Tip

"Group the array into two kinds of elements" is the partition pattern. Even/odd, zeros/non-zeros and negatives/positives are all solved the same way.

Approaches#

Approach 1: Sort the array#

Sorting puts all negatives first, but costs O(n log n) and does far more work than the problem asks for.

Approach 2: Extra array (keeps the original order)#

Copy all negatives into a new array, then all non-negatives, then copy back. This is O(n) time but O(n) extra space. Use it when the question asks you to keep the relative order of elements.

Approach 3: Two pointers (optimal)#

  1. Set left = 0 and right = n - 1.
  2. While left <= right:
    • If arr[left] is negative, it is in the right place: left++.
    • Else if arr[right] is non-negative, it is in the right place: right--.
    • Else arr[left] is positive and arr[right] is negative: swap them, then left++ and right--.
  3. When the pointers cross, every negative is on the left.
ApproachTimeExtra spaceKeeps order?
SortingO(n log n)O(1) to O(n)No (values get sorted)
Extra arrayO(n)O(n)Yes
Two pointersO(n)O(1)No

Dry run (animated)#

The two pointer approach on [-12, 11, -13, -5, 6, -7, 5, -3, -6]. Blue boxes are negatives already settled on the left, green boxes are non-negatives settled on the right, and orange boxes are the pair being swapped.

Animation: on -12 11 -13 -5 6 -7 5 -3 -6, pointer L finds positives and R finds negatives; they swap until all negatives (blue) are on the left and positives (green) on the right
  1. L skips -12 and stops at 11 (positive). R is at -6 (negative). Swap them: [-12, -6, -13, -5, 6, -7, 5, -3, 11].
  2. L skips -13 and -5 and stops at 6. R is at -3. Swap: [-12, -6, -13, -5, -3, -7, 5, 6, 11].
  3. L skips -7 and stops at 5. R also reaches 5, which is non-negative, so R moves left and the pointers cross. Done.

Only 2 swaps were needed to move all six negatives to the left.

Code#

Java#

Java
import java.util.Arrays;

public class Main {
    static void moveNegatives(int[] arr) {
        int left = 0, right = arr.length - 1;
        while (left <= right) {
            if (arr[left] < 0) {
                left++;                      // already on the correct side
            } else if (arr[right] >= 0) {
                right--;                     // already on the correct side
            } else {                         // left is positive, right is negative
                int t = arr[left]; arr[left] = arr[right]; arr[right] = t;
                left++;
                right--;
            }
        }
    }

    public static void main(String[] args) {
        int[] arr = {-12, 11, -13, -5, 6, -7, 5, -3, -6};
        moveNegatives(arr);
        System.out.println(Arrays.toString(arr)); // [-12, -6, -13, -5, -3, -7, 5, 6, 11]
    }
}

C#

C
#include <stdio.h>

static void swap(int *a, int *b) { int t = *a; *a = *b; *b = t; }

void moveNegatives(int arr[], int n) {
    int left = 0, right = n - 1;
    while (left <= right) {
        if (arr[left] < 0) {
            left++;                      /* already on the correct side */
        } else if (arr[right] >= 0) {
            right--;                     /* already on the correct side */
        } else {                         /* left is positive, right is negative */
            swap(&arr[left], &arr[right]);
            left++;
            right--;
        }
    }
}

int main(void) {
    int arr[] = {-12, 11, -13, -5, 6, -7, 5, -3, -6};
    int n = sizeof(arr) / sizeof(arr[0]);
    moveNegatives(arr, n);
    for (int i = 0; i < n; i++) printf("%d ", arr[i]); /* -12 -6 -13 -5 -3 -7 5 6 11 */
    printf("\n");
    return 0;
}

C++#

CPP
#include <iostream>
#include <vector>
using namespace std;

void moveNegatives(vector<int>& arr) {
    int left = 0, right = (int)arr.size() - 1;
    while (left <= right) {
        if (arr[left] < 0) {
            left++;                      // already on the correct side
        } else if (arr[right] >= 0) {
            right--;                     // already on the correct side
        } else {                         // left is positive, right is negative
            swap(arr[left++], arr[right--]);
        }
    }
}

int main() {
    vector<int> arr = {-12, 11, -13, -5, 6, -7, 5, -3, -6};
    moveNegatives(arr);
    for (int x : arr) cout << x << " "; // -12 -6 -13 -5 -3 -7 5 6 11
    cout << endl;
    return 0;
}

JavaScript#

JavaScript
function moveNegatives(arr) {
  let left = 0;
  let right = arr.length - 1;
  while (left <= right) {
    if (arr[left] < 0) {
      left++; // already on the correct side
    } else if (arr[right] >= 0) {
      right--; // already on the correct side
    } else {
      // left is positive, right is negative
      [arr[left], arr[right]] = [arr[right], arr[left]];
      left++;
      right--;
    }
  }
  return arr;
}

console.log(moveNegatives([-12, 11, -13, -5, 6, -7, 5, -3, -6]).join(" "));
// -12 -6 -13 -5 -3 -7 5 6 11

Python#

Python
def move_negatives(arr):
    left, right = 0, len(arr) - 1
    while left <= right:
        if arr[left] < 0:
            left += 1  # already on the correct side
        elif arr[right] >= 0:
            right -= 1  # already on the correct side
        else:  # left is positive, right is negative
            arr[left], arr[right] = arr[right], arr[left]
            left += 1
            right -= 1
    return arr


print(*move_negatives([-12, 11, -13, -5, 6, -7, 5, -3, -6]))
# -12 -6 -13 -5 -3 -7 5 6 11

Complexity analysis#

  • Time: O(n). Every loop step moves at least one pointer inward, so the loop runs at most n times.
  • Space: O(1). Just two pointers.

Edge cases and common mistakes#

  • Zero: decide which side it belongs to. Here zero counts as non-negative and goes to the right. If the question says otherwise, change the comparisons.
  • All negative or all positive: one pointer simply sweeps across without any swaps.
  • Order matters? The two pointer method does not keep the original order of elements. If the interviewer asks for a stable rearrangement, use the extra array approach or a modified insertion approach.
  • Empty or single element: the loop runs at most once and nothing breaks.
Note

This is the partition step of Quicksort with 0 as the pivot. Once you understand it, the Dutch National Flag problem (three groups instead of two) is a small step further.

Key takeaways#

  • Moving negatives to one side is a two-group partition, not a sort.
  • Left pointer looks for a positive, right pointer looks for a negative; swap and move both.
  • One pass, O(n) time and O(1) space, but the order inside each group can change.
  • Use an extra array when the relative order of elements must be preserved.