Example - Sort Colors

Dutch National Flag problem.

Problem: Sort array with values 00, 11, 22 in one pass.

Approach: Dutch National Flag with three pointers.

function sortColors(nums):
    low = mid = 0
    high = nums.length - 1

    while mid <= high:
        if nums[mid] == 0:
            swap(nums[low], nums[mid])
            low++; mid++
        else if nums[mid] == 1:
            mid++
        else:
            swap(nums[mid], nums[high])
            high--

Time: O(n)O(n). Space: O(1)O(1).