Move all 0s to the left and all 1s to the right of a binary array in one pass

Quick Overview

Rearrange an array of 0s and 1s in place so every 0 comes before every 1, using a single traversal of the array. It tests the two-pointer partition technique, loop invariants and constant extra space.

Move all 0s to the left and all 1s to the right of a binary array in one pass

Company: Toyota

Role: Software Engineer

Category: Coding & Algorithms

Difficulty: easy

Interview Round: Other

Given an array `nums` containing only `0`s and `1`s in random order, rearrange the array in place so that all `0`s appear on the left and all `1`s appear on the right. Return the rearranged array. The rearrangement must be done by traversing the array only once. ### Function Signature ```python def segregate(nums: list[int]) -> list[int]: ``` ### Rules - Rearrange `nums` in place and return that same list. ### Constraints - `1 <= len(nums) <= 10^5` - `nums[i]` is either `0` or `1` ### Examples ```text Input: nums = [0,1,0,1,0,0,1,1] Output: [0,0,0,0,1,1,1,1] ``` The input holds four 0s and four 1s, so the 0s fill the left half and the 1s fill the right half. ```text Input: nums = [1,1,1,0,0,1,0] Output: [0,0,0,1,1,1,1] ``` The 0s are at indices 3, 4 and 6, so there are three 0s and four 1s. Three 0s come first, then four 1s.

Overview: Rearrange an array of 0s and 1s in place so every 0 comes before every 1, using a single traversal of the array. It tests the two-pointer partition technique, loop invariants and constant extra space.

Toyota logo
Toyota
Nov 25, 2026
easySoftware EngineerOtherCoding & Algorithms
0
0

Given an array nums containing only 0s and 1s in random order, rearrange the array in place so that all 0s appear on the left and all 1s appear on the right.

Return the rearranged array. The rearrangement must be done by traversing the array only once.

Function Signature

def segregate(nums: list[int]) -> list[int]:

Rules

  • Rearrange nums in place and return that same list.

Constraints

  • 1 <= len(nums) <= 10^5
  • nums[i] is either 0 or 1

Examples

Input: nums = [0,1,0,1,0,0,1,1]
Output: [0,0,0,0,1,1,1,1]

The input holds four 0s and four 1s, so the 0s fill the left half and the 1s fill the right half.

Input: nums = [1,1,1,0,0,1,0]
Output: [0,0,0,1,1,1,1]

The 0s are at indices 3, 4 and 6, so there are three 0s and four 1s. Three 0s come first, then four 1s.