> Uploading knowledge... _
[░░░░░░░░░░░░░░░░░░░░░░░░] 0%
blog logo
> CHICIO CODING_Pixels. Code. Unplugged.

Sort Colors

Leetcode Problem 75: Sort Colors

Problem Summary

Given an array of n objects colored red (0), white (1), or blue (2), sort them in-place so that all reds come first, then whites, then blues. You must not use the built-in sort function.

Constraints:

  • The array has between 1 and 300 elements.
  • Each element is 0, 1, or 2.

Techniques

  • Array
  • Two Pointers
  • Sorting

Solution

function sortColors(nums: number[]): void {
    let colorsCount: Record<number, number> = {
        0: 0,
        1: 0,
        2: 0
    }

    for (let i = 0; i < nums.length; i++) {
        colorsCount[nums[i]] = colorsCount[nums[i]] + 1
    }

    for (let i = 0; i < colorsCount[0]; i++) {
        nums[i] = 0
    }

    for (let i = colorsCount[0]; i < colorsCount[0] + colorsCount[1]; i++) {
        nums[i] = 1
    }

    for (let i = colorsCount[0] + colorsCount[1]; i < nums.length; i++) {
        nums[i] = 2
    }
};

console.log(sortColors([2,0,2,1,1,0]))