Complete-Preparation

πŸŽ‰ One-stop destination for all your technical interview Preparation πŸŽ‰

View the Project on GitHub

75. Sort Colors 🌟🌟

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.

O(N log N) Time Complexity with sort function.

O(N)+O(N) Time using counting sort.

O(N) Time, 3 Pointers, dutch national flag algorithm.

Code

class Solution {
public:
    void sortColors(vector<int>& nums) {
        int lo = 0;
        int hi = nums.size() - 1;
        int mid = 0;

        while (mid <= hi)
        {
            switch (nums[mid])
            {
            case 0:
                swap(nums[lo++], nums[mid++]);
                break;
            case 1:
                mid++;
                break;
            case 2:
                swap(nums[mid], nums[hi--]);
                break;
            }
        }
    }
};