KatInterview

75. Sort Colors

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks us to sort an array containing three distinct values (0, 1, and 2), representing colors, in-place. The final arrangement must have all 0s first, followed by all 1s, and then all 2s. We are not allowed to use any library sort functions. This is a classic partitioning problem and the follow-up question hints at a one-pass, constant-space solution.

Solution

Sort Colors in Python

class Solution:
    def sortColors(self, nums: List[int]) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        # p0: pointer for the boundary of 0s.
        # p2: pointer for the boundary of 2s.
        # curr: current pointer.
        p0, curr, p2 = 0, 0, len(nums) - 1

        while curr <= p2:
            if nums[curr] == 0:
                # If the current element is 0, swap it with the element at p0.
                nums[p0], nums[curr] = nums[curr], nums[p0]
                # Move both pointers forward.
                p0 += 1
                curr += 1
            elif nums[curr] == 2:
                # If the current element is 2, swap it with the element at p2.
                nums[p2], nums[curr] = nums[curr], nums[p2]
                # Move p2 pointer backward.
                p2 -= 1
                # NOTE: Do not increment curr, as the swapped element at curr
                # needs to be processed.
            else: # nums[curr] == 1
                # If the current element is 1, it is in the right place (for now).
                # Move to the next element.
                curr += 1

Sort Colors in Java

class Solution {
    public void sortColors(int[] nums) {
        // p0 points to the end of the zero-section (exclusive)
        // p2 points to the start of the two-section (exclusive)
        // curr is the current element under consideration
        int p0 = 0, curr = 0;
        int p2 = nums.length - 1;

        while (curr <= p2) {
            if (nums[curr] == 0) {
                // If current element is 0, swap it with the element at p0
                int temp = nums[p0];
                nums[p0] = nums[curr];
                nums[curr] = temp;
                // Both p0 and curr pointers move one step forward
                p0++;
                curr++;
            } else if (nums[curr] == 2) {
                // If current element is 2, swap it with the element at p2
                int temp = nums[p2];
                nums[p2] = nums[curr];
                nums[curr] = temp;
                // p2 pointer moves one step backward
                p2--;
                // NOTE: curr pointer does not move. The new element at nums[curr]
                // needs to be processed in the next iteration.
            } else { // nums[curr] == 1
                // If current element is 1, it's in the correct potential place.
                // Just move curr pointer one step forward.
                curr++;
            }
        }
    }
}

Sort Colors in C++

class Solution {
public:
    void sortColors(vector<int>& nums) {
        // p0 points to the end of the zero-section (exclusive)
        // p2 points to the start of the two-section (exclusive)
        // curr is the current element under consideration
        int p0 = 0, curr = 0;
        int p2 = nums.size() - 1;

        while (curr <= p2) {
            if (nums[curr] == 0) {
                // If current element is 0, swap it with the element at p0
                swap(nums[curr], nums[p0]);
                // Both p0 and curr pointers move one step forward
                p0++;
                curr++;
            } else if (nums[curr] == 2) {
                // If current element is 2, swap it with the element at p2
                swap(nums[curr], nums[p2]);
                // p2 pointer moves one step backward
                p2--;
                // NOTE: curr pointer does not move. The new element at nums[curr]
                // needs to be processed in the next iteration.
            } else { // nums[curr] == 1
                // If current element is 1, it's in the correct potential place.
                // Just move curr pointer one step forward.
                curr++;
            }
        }
    }
};

Sort Colors in TypeScript

/**
 Do not return anything, modify nums in-place instead.
 */
function sortColors(nums: number[]): void {
    // p0: pointer for the boundary of 0s.
    // p2: pointer for the boundary of 2s.
    // curr: current pointer.
    let p0 = 0, curr = 0;
    let p2 = nums.length - 1;

    // Helper function for swapping elements.
    const swap = (i: number, j: number) => {
        [nums[i], nums[j]] = [nums[j], nums[i]];
    };

    while (curr <= p2) {
        if (nums[curr] === 0) {
            // If the current element is 0, swap it with the element at p0.
            swap(p0, curr);
            // Move both pointers forward.
            p0++;
            curr++;
        } else if (nums[curr] === 2) {
            // If the current element is 2, swap it with the element at p2.
            swap(p2, curr);
            // Move p2 pointer backward.
            p2--;
            // NOTE: Do not increment curr, as the swapped element at curr
            // needs to be processed.
        } else { // nums[curr] === 1
            // If the current element is 1, it is in the right place (for now).
            // Move to the next element.
            curr++;
        }
    }
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.