75. Sort Colors

Sort Colors (LeetCode 75) is a Medium Data Structures and Algorithms interview problem you can solve, run and submit on Thita.ai. It belongs to the Two Pointers pattern, in the In-place Array Modification subpattern.

How to solve Sort Colors

Sort Colors is a In-Place Array Modification problem, part of Two Pointers. Learn in-place array modification using two pointers. Remove duplicates, move zeroes, and sort colors efficiently.

Work towards the solution in these steps:

  1. A rather straight forward solution is a two-pass algorithm using counting sort.
  2. Iterate the array counting number of 0's, 1's, and 2's.
  3. Overwrite array with the total number of 0's, then 1's and followed by 2's.

The reference solution runs in O(n) time and O(1) space.

The Sort Colors solution and editorial walks through the full approach with reference code.

Problem statement

Given an array nums with n objects colored red, white, or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white, and blue.

We will use the integers 0, 1, and 2 to represent the color red, white, and blue, respectively.

You must solve this problem without using the library's sort function.

Example 1:

Input: nums = [2,0,2,1,1,0] Output: [0,0,1,1,2,2]

Example 2:

Input: nums = [2,0,1] Output: [0,1,2]

Constraints:

- n == nums.length

- 1 <= n <= 300

- nums[i] is either 0, 1, or 2.

Follow up: Could you come up with a one-pass algorithm using only constant extra space?

Topics and companies

Topics: Array, Two Pointers, Sorting.

Reported in interviews at Microsoft, Facebook, eBay, Amazon, Oracle, Adobe, Nvidia, Expedia.

How to practise Sort Colors on Thita.ai

Starter code is provided in C, C#, C++, Go, Java, JavaScript and Python. Your solution runs against 5 test cases for this problem, with the AI coach available for a hint when you are stuck rather than a finished answer. The reference solution runs in O(n) time and O(1) space.

Open Sort Colors in the code editor, or read the Sort Colors editorial for a worked solution with its approach and complexity analysis.

Where Sort Colors sits in the DSA pattern sheet

Problems related to Sort Colors

Other problems that use the same In-place Array Modification and Two Pointers techniques:

Sort Colors FAQ

What is the LeetCode number of Sort Colors?

Sort Colors is LeetCode problem 75, rated Medium.

What pattern is used to solve Sort Colors?

Sort Colors is a In-Place Array Modification problem. It belongs to the Two Pointers pattern, in the In-place Array Modification subpattern.

What is the time complexity of Sort Colors?

The reference solution runs in O(n) time and O(1) space.

Which companies ask Sort Colors?

Sort Colors has been reported in interviews at Microsoft, Facebook, eBay, Amazon, Oracle, Adobe, Nvidia, Expedia.

Preparing this workspace.