โ† Amazon questions
CodingReported in a candidate post, Jul 2025

Binary array sorting

Filed under Amazon

Free read 2 of 3

Maintain two pointers: left starting at 0 and right at len(nums) - 1.

The question

Given a binary array nums consisting of only 0s and 1s, sort the array in-place without using any built-in sort functions.

Constraints

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

Examples

Input
nums = [1, 0, 1, 1, 0, 0, 1]
Output
[0, 0, 0, 1, 1, 1, 1]
Why
All 0s moved to the front and 1s to the back.
Input
nums = [0, 0, 0]
Output
[0, 0, 0]
Why
Array contains only 0s, remains unchanged.

Approach

  1. Maintain two pointers: left starting at 0 and right at len(nums) - 1.

Solution

O(n) time, O(1) space

Python
class Solution:
    def sortBinaryArray(self, nums: list[int]) -> list[int]:
        left, right = 0, len(nums) - 1
        while left < right:
            while left < right and nums[left] == 0:
                left += 1
            while left < right and nums[right] == 1:
                right -= 1
            if left < right:
                nums[left], nums[right] = nums[right], nums[left]
                left += 1
                right -= 1
        return nums

Tips

  • What they are testing: Tests two-pointer manipulation and in-place swapping without extra memory.
  • Common mistake: Using extra space or accidentally overwriting elements when using count-and-fill instead of swapping.

Related Amazon questions

Collected from public candidate posts and coding forums. Updated Nov 2026.