Problem 75

Abstract / Summary

Given an array with only 0 1 and 2 sort it in place so that all 0s come first then 1s then 2s

Note

The full problem description, including helpful examples, can be found on LeetCode.

C++ 0075.cpp

class Solution {
public:
    void sortColors(vector<int>& nums) {
        vector<int> freq(3, 0);
        for (auto n : nums)
            freq[n]++;

        nums.clear();

        nums.insert(nums.end(), freq[0], 0);
        nums.insert(nums.end(), freq[1], 1);
        nums.insert(nums.end(), freq[2], 2);
    }
};
14 lines | 331 bytes | submitted August 8, 2023 | GitHub   tab size 4

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 70% (5+ million submissions).

Typical patterns to solve this problem:
  • Array
  • Sorting
  • Two Pointers
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation solves the classic “sort colors” problem, where an input array contains only the integers 0, 1, and 2, representing three distinct colors. The algorithm rearranges the elements so that all 0s appear first, followed by 1s, and finally 2s. It achieves this by counting the occurrences of each value and then reconstructing the array based on those counts. The approach is deterministic, runs in linear time with respect to the length of the input, and uses only a small, fixed amount of auxiliary storage.

Frequency Counting

The first logical block creates a three-element frequency vector initialized to zero. It then iterates over the original nums vector, incrementing the appropriate counter for each element.

vector<int> freq(3, 0);
for (auto n : nums)
    freq[n]++;

Because the input domain is limited to the indices 0, 1, 2, the freq vector directly maps each possible value to its count. This eliminates the need for conditional branches or hash-based structures, keeping the operation tight and cache-friendly.

Clearing the Original Container

After the frequencies have been recorded, the original nums vector is cleared. This step discards the previous ordering and prepares the container for a fresh insertion sequence.

nums.clear();

Calling clear() retains the allocated capacity of the vector, which means that subsequent insertions can reuse the existing memory block without triggering additional allocations. This subtle reuse contributes to the overall efficiency, especially for large inputs.

Rebuilding the Sorted Sequence

The final phase repopulates nums by inserting the appropriate number of each color in order. The insert method is invoked three times, each time specifying the count of elements to add and the value to insert.

nums.insert(nums.end(), freq[0], 0);
nums.insert(nums.end(), freq[1], 1);
nums.insert(nums.end(), freq[2], 2);

Using the overload of insert that takes a count and a value allows the implementation to add a contiguous block of identical elements in a single call. Internally, this translates to a bulk memory operation rather than a per-element push, reducing loop overhead and improving data locality.

Edge Cases Handled

The algorithm gracefully handles an empty input vector. In that scenario, the frequency counters remain zero, the clear() call leaves the vector empty, and the three insert calls each attempt to add zero elements, resulting in no change to the container.

When the input consists exclusively of a single color-such as all 0s, all 1s, or all 2s-the frequency vector records a non-zero count for only one index. The reconstruction phase then inserts a block of that single value while the other two insert calls add nothing, yielding a correctly sorted array without extra work.

If the input already appears in sorted order, the algorithm still performs the counting and rebuilding steps, but the final arrangement matches the original ordering. The method does not rely on any assumptions about the initial distribution, ensuring correctness regardless of pre-existing order.

Performance Optimizations

The design leverages a counting sort paradigm, which is optimal for a fixed, small range of integer keys. By avoiding comparison-based sorting, the implementation eliminates the overhead associated with element swaps and recursive partitioning.

Memory reuse is achieved through the combination of clear() and the subsequent insert calls. Because clear() does not deallocate the underlying storage, the vector’s capacity remains sufficient for the final size, preventing repeated allocations and deallocations that could degrade performance.

Bulk insertion via vector::insert with a count argument reduces the number of function calls and loop iterations required to rebuild the array. This approach allows the standard library to perform a single contiguous memory copy for each color block, which is typically faster than inserting elements one by one.

Overall, the code exhibits a tight control flow with minimal branching, leverages contiguous memory operations, and confines auxiliary storage to a constant-size array, all of which contribute to an efficient execution profile for the problem at hand.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a big box filled with lots of mixed up crayons that are only red, white, and blue. To tidy them up, the first thing is to count how many of each color are in the box. A small list is made to keep track of the count for red, the count for white, and the count for blue.

Once every single crayon is counted, the box is emptied out so it is perfectly clean. Then, all the red crayons are put back first, followed by all the white crayons, and finally all the blue crayons go in last. Now, all the matching colors are sitting together in a neat row, just like magic.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 7 | μ = 7.11 | σ = 1.20

Complexity Analysis

Time: linear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python Java C# Rust Go TS
LeetcodeHelp C++ Python Java
MemoryLimitExceeded C++ Python
Progiez C++ Python Java
github AdelDaniel Dart
aylei Rust
begeekmyfriend C
BigEggStudy C#
black-shadows C++
charles-wangkai Java
chenyanzhe C++
Dijkstra-Edu C++
everthis JS
fartem Ruby
FelixFan1122 C#
fengvyi C++
fpdjsns C++
gaosq0604 Python
Garvit244 Python
gouthampradhan Java
halfrost Go
haoel C++
JoshCrozier JS
keineahnung2345 C++
Krazune C
lennylxx C
linouk23 C++
lkwq007 Python
luangong C++
muhammadfarhankt Go
qiyuangong Python
ruoru Rust
shreymehul C#
sonugiri1043 C++
suxrobGM C#
varunu28 Java
vli02 C
vthwang Java
wisdompeak C++
YuriSpiridonov Python
zfang399 C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, C#, Go, Java, Python, Rust, TypeScript
LeetcodeHelp C++, Java, Python
MemoryLimitExceeded Python, C++
Progiez C++, Java, Python
AdelDaniel Dart
aylei Rust
begeekmyfriend C
BigEggStudy C#
black-shadows C++, C++
charles-wangkai Java
chenyanzhe C++
Dijkstra-Edu C++
everthis JavaScript
fartem Ruby
FelixFan1122 C#
fengvyi C++
fpdjsns C++
gaosq0604 Python
Garvit244 Python
gouthampradhan Java
halfrost Go
haoel C++
JoshCrozier JavaScript
keineahnung2345 C++
Krazune C
lennylxx C
linouk23 C++
lkwq007 Python
luangong C++
muhammadfarhankt Go
qiyuangong Python
ruoru Rust
shreymehul C#
sonugiri1043 C++
suxrobGM C#
varunu28 Java
vli02 C
vthwang Java
wisdompeak C++
YuriSpiridonov Python
zfang399 C++
59 links | 43 authors | 11 languages

Videos

These are a few popular YouTube videos for this problem:
YouTube video 'Sort Colors - Quicksort Partition - Leetcode 75 - Python'
NeetCode 16 mins
Sort Colors - Quicksort Partition - Leetcode 75 - Python
YouTube video 'Sort colors | Leetcode #75'
Techdose 7 mins
Sort colors | Leetcode #75
YouTube video 'Sort Colors (LeetCode 75) | Dutch National Flag Problem | Full Solution with Visuals and Animations'
Nikhil Lohia 16 mins
Sort Colors (LeetCode 75) | Dutch National Flag Problem | Full Solution with Visuals and Animations
YouTube video 'Sort Colors | LeetCode 75 | C++, Java, Python'
Knowledge Center 19 mins
Sort Colors | LeetCode 75 | C++, Java, Python
YouTube video '[Java] Leetcode 75. Sort Colors [Two Pointers #9]'
Eric Programming 9 mins
[Java] Leetcode 75. Sort Colors [Two Pointers #9]
YouTube video 'LeetCode 75. Sort Colors  [Solution + Code Explained ]'
jayati tiwari 9 mins
LeetCode 75. Sort Colors [Solution + Code Explained ]
YouTube video '75. Sort Colors | 2 Pointers | Super Important Interview Question | 100Days 100K Placements'
Aryan Mittal 21 mins
75. Sort Colors | 2 Pointers | Super Important Interview Question | 100Days 100K Placements
YouTube video 'Sort Colors - 75. LeetCode - Java'
Teddy Smith 10 mins
Sort Colors - 75. LeetCode - Java
YouTube video '12. Sort Colors | Arrays - Medium | Learn DSA | Leetcode 75'
Ayushi Sharma 14 mins
12. Sort Colors | Arrays - Medium | Learn DSA | Leetcode 75
YouTube video '[English] LeetCode 75. Sort Colors'
happygirlzt 8 mins
[English] LeetCode 75. Sort Colors
YouTube video 'Sort Colors - LeetCode 75 - Python - Visually Explained'
Hello Byte 4 mins
Sort Colors - LeetCode 75 - Python - Visually Explained
YouTube video 'Daily Leetcode #1873: May 17, 2025 - 75. Sort Colors'
Programming Live with Larry 15 mins
Daily Leetcode #1873: May 17, 2025 - 75. Sort Colors
YouTube video '[Chinese] LeetCode 75. Sort Colors'
happygirlzt 7 mins
[Chinese] LeetCode 75. Sort Colors
YouTube video 'Sort Colors | Day 11 | [June LeetCoding Challenge] [Leetcode #75] [2020]'
Algorithms Made Easy 5 mins
Sort Colors | Day 11 | [June LeetCoding Challenge] [Leetcode #75] [2020]
YouTube video 'LeetCode 75| Sort Colors| dutch national flag leetcode | MAANG Interview Questions | Must do DSA'
Code Thoughts 7 mins
LeetCode 75| Sort Colors| dutch national flag leetcode | MAANG Interview Questions | Must do DSA
YouTube video 'Sort Colors | Leetcode 75 | Live coding session 🔥🔥🔥'
Coding Decoded 9 mins
Sort Colors | Leetcode 75 | Live coding session 🔥🔥🔥
YouTube video 'Daily Leetcode #1534: Jun 12, 2024 - 75. Sort Colors'
Programming Live with Larry 12 mins
Daily Leetcode #1534: Jun 12, 2024 - 75. Sort Colors
YouTube video 'Sort Colors  (LeetCode 75) (Intution Explained) (DNF) (3 Approaches)'
CodeWithARB 30 mins
Sort Colors (LeetCode 75) (Intution Explained) (DNF) (3 Approaches)
YouTube video 'sort colors | sort colors leetcode | sort 012 array | leetcode problem 75'
Naresh Gupta 10 mins
sort colors | sort colors leetcode | sort 012 array | leetcode problem 75
YouTube video 'Sort Colors || leetcode 75 || leetcode medium || interview problem || c++ solution'
code Explainer 5 mins
Sort Colors || leetcode 75 || leetcode medium || interview problem || c++ solution
20 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

19 easy 42 medium 2 hard
64 solutions   August 8, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality