PIXELBANKv8.2.1
Menu

Sort Colors

Given an array with n objects colored red (0), white (1), or blue (2), sort them in-place so same colors are adjacent in order 0, 1, 2.

Output space-separated.

Example:

Input:
2,0,2,1,1,0
Output:
0 0 1 1 2 2
Reasoning:
  • The input array is 2, 0, 2, 1, 1, 0, which needs to be sorted in-place with same colors adjacent in order 0, 1, 2.
  • We initialize three pointers: one at the start, one at the end, and one for scanning the array, to track the positions of 0, 1, and 2.
  • As we scan the array, we swap elements to maintain the order: if the current element is 0, we swap it with the element at the start pointer and move both pointers forward; if it's 2, we swap it with the element at the end pointer and move the end pointer backward.
  • After scanning the entire array, the elements are sorted in-place as 0, 0, 1, 1, 2, 2, which is then output as space-separated values: 0 0 1 1 2 2.

Constraints:

  • 1 <= len(nums) <= 300
  • nums[i] is 0, 1, or 2
Editor

Test Results

0/0
Run code to see test results.