05 May 2023PythonUnknown

Sort Colors

notes and solution files for sort colors.

this entry collects the solution files i have for sort colors. i may expand it with a fuller write-up later, but the implementation files are already here.

available solution files

  • Python sort-colors/solution.py

Solution files

Pythonsort-colors/solution.py
from typing import List


class Solution:
    def sortColors(self, nums: List[int]) -> None:
        left = class="syntax-number">0
        current = class="syntax-number">0
        right = len(nums) - class="syntax-number">1

        while current <= right:
            color = nums[current]

            if color == class="syntax-number">0:
                nums[left], nums[current] = nums[current], nums[left]
                left += class="syntax-number">1
                current += class="syntax-number">1
                continue

            if color == class="syntax-number">2:
                nums[right], nums[current] = nums[current], nums[right]
                right -= class="syntax-number">1
                continue

            current += class="syntax-number">1