75-days-dsa-challenge

Ninja technique🥷 to ACE DSA Interviews.

View the Project on GitHub

75. Sort Colors (Medium)

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;
            }
        }
    }
};