v9.1.1
Menu

Sort Colors

mediumPROSorting & SearchingNetflix DSA

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.

The function modifies nums in place and returns nothing; the tests print the sorted nums space-separated.

Example

Input
2,0,2,1,1,0
Output
0 0 1 1 2 2
Reasoning
  • The input 2,0,2,1,1,0 is a list of n=6n = 6 colour codes: 00 = red, 11 = white, 22 = blue. Each value is only a label, so the task is grouping, not general ordering.
  • Tally the colours: red appears 22 times (positions 11 and 55), white 22 times (positions 33 and 44), blue 22 times (positions 00 and 22). The total is 2+2+2=62 + 2 + 2 = 6.
  • Rearranging never creates or destroys a value, so the result must hold exactly those tallies: reds fill positions 00 to 11, whites positions 22 to 33, blues positions 44 to 55.
  • That gives 0 0 1 1 2 2, the same six numbers in non-decreasing order, printed space-separated.
  • Notice that "in-place" means the list passed in is itself changed: after the call, nums holds the grouped order, and nothing needs to be returned. With kk reds and ww whites, the blues always start at position k+wk + w.

Constraints

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

Learn this in

More from Netflix DSA

PRO

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test results

Sign in to run your code against the test cases.