← Home

75. Sort Colors

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
two pointersC++Markdown
75

This problem looks busy at first, but the accepted solution is built around one steady invariant. For 75. Sort Colors, the solution in this repository is mainly a two pointers solution.

Guide

What?

We want to turn the problem statement into a smaller set of decisions the computer can repeat safely. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: two pointers, sliding window.

The notes already sitting in the source point us in the right direction:

  • counting sort

Guide

When?

This pattern shows up when the brute force version has too many repeated checks, too many possible branches, or too much bookkeeping to do by hand. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are sortColors.

Guide

Why?

The win comes from making each line carry responsibility: store the useful state, discard the rest, keep moving.

  • A map keeps the lookup side cheap; the code pays a little memory to avoid repeated searching.

Guide

How?

Walk through the solution in this order:

  1. Start from the smallest reliable state.
  2. Expand one legal move at a time.
  3. Cache, count, or merge information as soon as it becomes settled.
  4. Let the final stored value answer the original question.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01//counting sort
02//Runtime: 4 ms, faster than 69.48% of C++ online submissions for Sort Colors.
03//Memory Usage: 7.8 MB, less than 100.00% of C++ online submissions for Sort Colors.
04class Solution {
05public:
06    void sortColors(vector<int>& nums) {
07        map<int, int> counter;
08        for(int& num : nums){
09            counter[num]++;
10        }
11        
12        int cur = 0;
13        for(auto it = counter.begin(); it != counter.end(); it++){
14            while(it->second){
15                nums[cur++] = it->first;
16                it->second--;
17            }
18        }
19    }
20};
21
22//two pointer, dutch partitioning problem
23//https://leetcode.com/problems/sort-colors/discuss/26679/C%2B%2B-one-pass-concise-solution.
24//https://leetcode.com/problems/sort-colors/discuss/26481/Python-O(n)-1-pass-in-place-solution-with-explanation
25class Solution {
26public:
27    void sortColors(vector<int>& nums) {
28        int left = 0, cur = 0, right = nums.size()-1;
29        /*
30        left: right boundary of 0(exclusive), serves as the next position to place 0
31        right: left boundary of 2(exclusive), serves as the next position to place 2
32        cur: the right boundary of 1(inclusive)
33        */
34        while (cur <= right) {
35            // cout << left << " " << cur << " " << right << endl;
36            if (nums[cur] == 0){
37                /*
38                put the number 0 to the position "left"
39                nums[left] will be put in nums[cur], it will be visited later
40                */
41                swap(nums[cur++], nums[left++]);
42            }else if (nums[cur] == 2){
43                /*
44                put the number 0 to the position "right"
45                nums[right] will be put in nums[cur], it will be visited later
46                (look at the condition cur <= right)
47                */
48                swap(nums[cur], nums[right--]);
49            }else{
50                /*
51                the number "1" is in right position,
52                so just move forward
53                */
54                cur++;
55            }
56            
57            // for(int& num : nums){
58            //     cout << num << " ";
59            // }
60            // cout << endl;
61        }
62    }
63};

Cost

Complexity

Time
O(n) to O(n log n), depending on the dominant loop or data structure operation
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(n) in the usual case for auxiliary containers or recursion
Auxiliary state plus the answer structure where the problem requires one.