Back to ArraysSegregate 0s and 1s
Easy

Segregate 0s and 1s

EasyOptionalDutch National FlagTwo Pointers

Given an array that only contains 0s and 1s, rearrange it in place so all the 0s come before all the 1s, in a single pass.

Examples

Example 1

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

Explanation: All three 0s move to the front and all three 1s move to the back; the exact order within each group isn't required.

Example 2

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

Explanation: The same two-way partition is produced even when the input arrives 1s-first.

Example 3

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

Explanation: An array of a single repeated value is already segregated.

Constraints

  • 1 <= nums.length <= 10^5
  • nums[i] is either 0 or 1

Loading editor…

Code execution is coming soon.