InferenceAI

Enter at least two characters to search.

Start free

Sort Three Colours

mediumTwo Pointers25 min25 XP

Sort a list containing only 0, 1 and 2 in a single pass with O(1)O(1) extra space (the Dutch national flag problem). Return the sorted list.

Examples

EXAMPLE WALKTHROUGHmixed

A guided view of the published example, not a trace of your code.

INPUT[[2,0,2,1,1,0]]
TASKsort_colours()
EXPECTED OUTPUT[0,0,1,1,2,2]

Start with the input values shown in this example.

Example 1 of 3

Input: nums = [2,0,2,1,1,0]

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

Explanation: mixed

Input: nums = [2,0,1]

Output: [0,1,2]

Explanation: three values

Input: nums = []

Output: []

Explanation: empty

Hint 1

Keep three pointers: the end of the 0s, the current element, and the start of the 2s.

Topics

DSATwo PointersPython