1. Standard Comparison Sort
Intuition
Sort the array using an in-place comparison sort (like Quicksort or built-in sort).
Algorithm
- 1. Apply standard comparison sort on the input array nums.
- 2. The numbers 0, 1, and 2 naturally arrange themselves in non-decreasing order.
- 3. Time complexity is O(N log N), which fails the linear-time requirement.
Brute Force Comparison Sorting Trace
2 of 2 questions left todayPhase 1 — Step 1: Pass 1, Swap 1: Compare index 0 (2) and index 1 (0)
Phase 1 — Step 1: Pass 1, Swap 1: Compare index 0 (2) and index 1 (0). 2 > 0, swap them.
#include <iostream>#include <vector>#include <string>#include <algorithm>#include <unordered_map>#include <unordered_set>#include <queue>#include <stack>#include <numeric>#include <climits> using namespace std; class Solution {public: void sortColors(vector<int>& nums) { std::sort(nums.begin(), nums.end()); }}; int main() { Solution sol; vector<int> nums = {2, 0, 2, 1, 1, 0}; sol.sortColors(nums); cout << "Sorted Colors: "; for (int x : nums) cout << x << " "; cout << endl; return 0;}Time & Space Complexity
- Time complexity:
O(N log N)— Standard comparison sorting performs O(N log N) element comparisons. - Space complexity:
O(1)— In-place QuickSort uses O(log N) recursion stack, or O(1) auxiliary space.
Why Brute Force Doesn't Scale:
For N = 105, quadratic O(N2) approaches require ~1010 operations, exceeding the standard 1-second CPU budget.
The optimal approach processes N elements in a single or logarithmic pass, completing in under 10ms with minimal memory footprint.