Leetcode 75. Sort Colors

Intuition

The basic intuition comes from sorting.

Approach

In the naive approach, we can sort the array using inbuilt sorting function. The time complexity will be O(N*log(N)).

Optimize:
Since we are sorting only three number…


This content originally appeared on DEV Community and was authored by Dev Nirwal

Intuition

The basic intuition comes from sorting.

Approach

In the naive approach, we can sort the array using inbuilt sorting function. The time complexity will be O(N*log(N)).

  • Optimize: Since we are sorting only three numbers, we can use the concept of counting sort. Keep track of number of zeros and number of ones in the array. # Complexity
  • Time complexity: O(N)

  • Space complexity: O(1)

Code

class Solution {
    public void sortColors(int[] nums) {
        int countZero = 0;
        int countOne  =  0;
        for(int num: nums){
            switch(num){
                case 0:
                    countZero++;
                    break;
                case 1:
                    countOne++;
            }
        }
        int currentIndex = -1;
        while(0<countZero--){
            nums[++currentIndex] = 0;
            // countZero--;
        }
        while(0<countOne--){
            nums[++currentIndex] = 1;
            // countOne--;
        }
        while(currentIndex<nums.length-1){
            nums[++currentIndex] = 2;
        }
    }
}

GitHub repo for more solutions: Git
Leetcode profile: Leetcode: devn007


This content originally appeared on DEV Community and was authored by Dev Nirwal


Print Share Comment Cite Upload Translate Updates
APA

Dev Nirwal | Sciencx (2025-01-11T08:07:57+00:00) Leetcode 75. Sort Colors. Retrieved from https://www.scien.cx/2025/01/11/leetcode-75-sort-colors/

MLA
" » Leetcode 75. Sort Colors." Dev Nirwal | Sciencx - Saturday January 11, 2025, https://www.scien.cx/2025/01/11/leetcode-75-sort-colors/
HARVARD
Dev Nirwal | Sciencx Saturday January 11, 2025 » Leetcode 75. Sort Colors., viewed ,<https://www.scien.cx/2025/01/11/leetcode-75-sort-colors/>
VANCOUVER
Dev Nirwal | Sciencx - » Leetcode 75. Sort Colors. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2025/01/11/leetcode-75-sort-colors/
CHICAGO
" » Leetcode 75. Sort Colors." Dev Nirwal | Sciencx - Accessed . https://www.scien.cx/2025/01/11/leetcode-75-sort-colors/
IEEE
" » Leetcode 75. Sort Colors." Dev Nirwal | Sciencx [Online]. Available: https://www.scien.cx/2025/01/11/leetcode-75-sort-colors/. [Accessed: ]
rf:citation
» Leetcode 75. Sort Colors | Dev Nirwal | Sciencx | https://www.scien.cx/2025/01/11/leetcode-75-sort-colors/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.