LeetCode 75: Sort Colors Solution

Master LeetCode problem 75 (Sort Colors), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

75. Sort Colors

Problem Explanation

Explanation

To solve this problem, we can use the Dutch National Flag algorithm. The idea is to partition the array into three sections: 0s, 1s, and 2s. We maintain three pointers: low, mid, and high. The low pointer points to the end of the section of 0s, the mid pointer is used to iterate through the array, and the high pointer points to the beginning of the section of 2s.

We iterate through the array and perform the following steps:

  • If nums[mid] == 0, we swap nums[low] with nums[mid], increment low and mid.
  • If nums[mid] == 1, we simply increment mid.
  • If nums[mid] == 2, we swap nums[mid] with nums[high], decrement high.

This process ensures that after partitioning, all 0s will be on the left, all 1s in the middle, and all 2s on the right.

Time Complexity: O(n) where n is the number of elements in the array. Space Complexity: O(1)

Solution Code

class Solution {
    public void sortColors(int[] nums) {
        int low = 0, mid = 0, high = nums.length - 1;
        while (mid <= high) {
            if (nums[mid] == 0) {
                int temp = nums[low];
                nums[low] = nums[mid];
                nums[mid] = temp;
                low++;
                mid++;
            } else if (nums[mid] == 1) {
                mid++;
            } else {
                int temp = nums[mid];
                nums[mid] = nums[high];
                nums[high] = temp;
                high--;
            }
        }
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 75 (Sort Colors)?

This page provides optimized solutions for LeetCode problem 75 (Sort Colors) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 75 (Sort Colors)?

The time complexity for LeetCode 75 (Sort Colors) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 75 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 75 in Java, C++, or Python.

Back to LeetCode Solutions