Skip to content
Katabench
Try free

Sort Colors

Medium About 20 min Free, no account needed

Sort an array of 0s, 1s and 2s in a single pass.

The brief

Given an array nums containing only 0, 1 and 2 (red, white, blue), return the array sorted ascending, without calling a library sort.

The performance bar

The obvious approach hand-rolls a quadratic sort, O(n2), which is far too slow on the hidden 150,000-element test. You need O(n). The tiny value domain (only 0, 1, 2) is the lever.

Starter code

C#
using System;

public class Solution
{
    // TODO: return nums sorted ascending (values are only 0, 1 and 2).
    public int[] SortColors(int[] nums)
    {
        throw new NotImplementedException();
    }
}

How it is graded

Visible examples help you iterate. Hidden tests then cover edge cases and larger inputs, and every test reports server-measured time and allocated bytes.

C# coding challenges →

What it practices

Two pointers
Walk a sorted or symmetric sequence from both ends, or fast and slow, instead of checking every pair.

Related katas