The Indian Engineer

Problem 75 Sort Colors

Posted on Last edited 3 mins

Sorting Two-Pointer Array

Problem Statement

Link - Problem 75

Question

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.

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

Solution

// Two loop solution
class Solution {
public:
    void sortColors(vector<int>& nums) {
       for(int i = 0;i<nums.size();i++)
       {
           for(int j = i+1;j<nums.size();j++)
           {
               if(nums[i]>nums[j])
            {
                int temp = nums[i];
                nums[i]=nums[j];
                nums[j]=temp;
            }
           }
       }
    }
};

Complexity Analysis

Explanation

1. Intuition

2. Implementation

Alternate Solution

class Solution {
public:
    void sortColors(vector<int>& nums) {
        int low = 0;
        int mid = 0;
        int high = nums.size()-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--;
            }
        }
    }
};
Intuition
Implementation

Shows a similarity to count sort. We can use the same approach to solve this problem. We can count the number of 0’s, 1’s, and 2’s and then fill the array accordingly. This will also solve the problem in O(N) time complexity.