17.Sort Colors(Sort array of 0, 1, 2)

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.

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

Solution : (Using 3 pointers)

Approach: Keep three pointers low=0, mid=0, high =0 if mid = 0 {swap (mid,low) and increment mid,low } if mid = 1 {incement mid} if mid = 2 {swap (mid,high) and decrement high}

class Solution
{
public:
    void sortColors(vector<int> &nums)
    {

        int l = 0;
        int h = nums.size() - 1;
        int m = 0;

        while (m <= h)
        {

            if (nums[m] == 0)
            {
                swap(nums[l], nums[m]);
                l++;
                m++;
            }
            else if (nums[m] == 1)
            {
                m++;
            }
            else if (nums[m] == 2)
            {
                swap(nums[m], nums[h]);
                h--;
            }
        }
    }
};

Time Complexity: O(n)

Last updated