Skip to main content

Sort Colors

In this page, we will be solve the Sort Colors problem using three different approaches: brute force, 3 Pointer, and Dutch National Flag Algo technique. We will provide the implementation of the solution in JavaScript, TypeScript, Python, Java, C++, and more.

Problem Description​

Given an array nums with n objects colored red, white, or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white, and blue.

We will use the integers 0, 1, and 2 to represent the color red, white, and blue, respectively.

You must solve this problem without using the library's sort function.

Examples​

Example 1:

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

Example 2:

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

Constraints​

  • n == nums.length
  • 1 <= n <= 300
  • nums[i] is either 0, 1, or 2.

Follow up: Could you come up with a one-pass algorithm using only constant extra space?


Solution for Sort Colors​

Intuition and Approach​

The problem can be solved using a brute force approach by sorting vector, 3 pointers, or the Dutch National Flag Algo. The brute force approach has a time complexity of O(nlog(n))O(nlog(n)), while the 3 Pointer and Dutch National Flag Algo techniques have a time complexity of O(n)O(n). The Dutch National Flag Algo approach is the most efficient and is recommended for large inputs.

Approach 1: Brute Force (Naive)​

We can simply Sort the Array and get Answer of it. But the time complexity will be for this goes to O(N*logN).

Codes in Different Languages​

Written by @aryan-1309
var sortColors = function(nums) {
nums.sort((a, b) => a - b);
};

Complexity Analysis​

  • Time Complexity: O(nlog(n))O(n log(n))
  • Space Complexity: O(1)O(1)
  • Where n is the length of the input array nums.

References​