Skip to content
Separate 0s and 1s

Separate 0s and 1s in an array – Single Iteration

🟢 Easy 🧩 Pattern – Arrays

Given an array which contains only zeroes and ones, we need to seperate them by putting the zeroes first followed by the ones.

Example

Input: 1  0  1  0  0  1  0  1  1
Output: 0  0  0  0  1  1  1  1  1

Input: 0 1 1 1 0 0 0 0 1 0 0 1 1 1 0 0 0
Output: 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1Code language: JavaScript (javascript)

Solution

The zeroPointer variable is used to keep track of the index where the next zero should be placed.

function separateZeroOne(nums) {
  let zeroPointer = 0;
  for (let i = 0; i < nums.length; i++) {
    if (nums[i] === 0) {
      const temp = nums[i];
      nums[i] = nums[zeroPointer];
      nums[zeroPointer] = temp;
      zeroPointer++;
    }
  }
  return nums;
}

const nums = [1, 0, 1, 0, 0, 1, 0, 1, 1];
console.log(separateZeroOne(nums));
//  [0, 0, 0, 0, 1, 1, 1, 1, 1]
Code language: JavaScript (javascript)
Back to Top
Tags: