dev-resources.site
for different kinds of informations.
Leetcode 75. Sort Colors
Published at
1/11/2025
Categories
java
sorting
algorithms
leetcode
Author
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
Articles
9 articles in total
Leetcode 75. Sort Colors
currently reading
Kadane's Algorithm: Leetcode 53 Maximum subarray
read article
Leetcode: 73 Set Matrix Zeroes
read article
Leetcode Solution - Github automation
read article
SMS Bomber App - Flutter
read article
Hacktoberfest - 2021
read article
Quoted Image App
read article
Shorti - Opensource URL Shortener
read article
Prank Sms Bomber
read article
Featured ones: