Leetcode 75: Sort Colors

grid47
grid47
Exploring patterns and algorithms
Oct 30, 2024 5 min read

A radiant sequence of colors gently sorting themselves in a peaceful, fluid motion.
Solution to LeetCode 75: Sort Colors Problem

You are given an array of integers where each element represents a color: 0 for red, 1 for white, and 2 for blue. Your task is to sort the array such that all reds (0) appear first, followed by whites (1), and finally blues (2). Solve the problem in one pass with constant extra space, without using any built-in sort functions.
Problem
Approach
Steps
Complexity
Input: The input consists of an array of integers where each integer is either 0, 1, or 2.
Example: nums = [1, 0, 2, 1, 0, 2]
Constraints:
• 1 <= n <= 300
• nums[i] is either 0, 1, or 2.
Output: Return the sorted array where all 0s (red) appear first, followed by 1s (white), and finally 2s (blue).
Example: [0, 0, 1, 1, 2, 2]
Constraints:
• The output should be a single array with the elements sorted according to the color order.
Goal: Sort the array in-place using a one-pass algorithm with constant space.
Steps:
• Use a three-pointer approach (Dutch National Flag algorithm):
• Set pointers i and j at the beginning and end of the array, respectively.
• Iterate through the array using a third pointer k to rearrange the elements by swapping them with the correct pointers.
Goal: The matrix contains only integers 0, 1, or 2, and its size is constrained.
Steps:
• 1 <= n <= 300
• nums[i] is either 0, 1, or 2.
Assumptions:
• The array will only contain the integers 0, 1, and 2.
• The array has at least one element.
Input: nums = [1, 0, 2, 1, 0, 2]
Explanation: By sorting the array, we move the 0s to the front, followed by the 1s and 2s, resulting in [0, 0, 1, 1, 2, 2].

Input: nums = [2, 1, 0]
Explanation: The array is sorted to [0, 1, 2], with all the 0s first, followed by 1s and 2s.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus