Sort a list of 0s, 1s and 2s in one pass
Coding problemMediumAsked in: GreyOrange
Given a list that holds only the values 0, 1 and 2, return it sorted: all 0s first, then all 1s, then all 2s.
The interview asks for one pass over the list with constant extra memory, without a built-in sort function and without counting the values first. The tests check the result; the one-pass rule is the point of the exercise.
Examples
Example 1
Input: nums = [2,0,2,1,1,0]
Output: [0,0,1,1,2,2]
Example 2
Input: nums = [2,0,1]
Output: [0,1,2]
Example 3
Input: nums = []
Output: []
Constraints
- The list holds between 0 and 100,000 values
- Each value is 0, 1 or 2
Run checks the 3 examples. Submit also runs the hidden tests: edge cases, large inputs and a time limit.
Run your code to see the results here. Ctrl or Cmd + Enter runs; add Shift to submit.