Back to DSA sheet

Sort Colors

MediumArrays
Open on LeetCodeAmazonGoogleMicrosoft

Given an array with values only 0, 1, or 2 (representing colors), sort it in place so all 0s come first, then 1s, then 2s. Do it in one pass without a library sort.

Input format (stdin): the first line has n. The second line has n values (each 0, 1, or 2). Output the sorted array, space separated.

Examples
Input: 6 2 0 2 1 1 0
Output: 0 0 1 1 2 2
Input: 3 2 0 1
Output: 0 1 2
Constraints
  • 1 <= n <= 300
  • nums[i] in {0, 1, 2}
Sheets
Blind 75Grind 75Love Babbar 450NeetCode 150NeetCode 250Striver A2Z
sort-colors.cpp3 sample tests
Loading editor
Test results

Run the sample tests to check your solution against expected output.

Custom input (stdin)
Output

Run your code to see its output.