Sort Colors (0s, 1s, 2s)

Problem

Sort an array containing only the values 0, 1 and 2.

Examples

Example 1
Input: [2,0,2,1,1,0]
Output: [0,0,1,1,2,2]
Example 2
Input: [2,2,1,0]
Output: [0,1,2,2]

Input and output use JSON-compatible values. For linked-list and tree questions, arrays represent the node structure as described above. Your code should implement solve(input).

Write your solutionImplement solve(input). Your draft is saved in this browser.
Advertisement

How to solve Sort Colors (0s, 1s, 2s)

Sort an array containing only the values 0, 1 and 2. Use three pointers to maintain regions for zeros, ones and twos. The reference implementation illustrates this approach; check the example and edge cases.

Time and space complexity

O(n) time and O(1) auxiliary space.

Practise and improve

Choose JavaScript, TypeScript or Python, complete the starter code, then select Run Tests. Request a hint when you need guidance, or choose View solution and confirm if you would like to study the reference implementation.