1. Brute Force (Built-in Comparison Sort)
Intuition
Passes the array into built-in sorting routines. While it satisfies the output format, it violates the single-pass linear time constraint.
Algorithm
- Step 1: Call standard library sort on nums.
- Step 2: Return or mutate in place.
Brute Force (Built-in Comparison Sort) Trace
2 of 2 questions left todayPhase 1 — Setup: Left pointer L anchors at 0
Phase 1 — Setup: Left pointer L anchors at 0. Scanner pointer R starts traversing the array.
#include <iostream>#include <vector>#include <algorithm> class Solution {public: void sortColors(std::vector<int>& nums) { std::sort(nums.begin(), nums.end()); }}; int main() { Solution sol; std::vector<int> nums = {2, 0, 2, 1, 1, 0}; sol.sortColors(nums); std::cout << "Sorted: "; for (int x : nums) std::cout << x << " "; std::cout << std::endl; return 0;}Time & Space Complexity
- Time complexity:
O(N^2)— Time complexity for Brute Force (Built-in Comparison Sort). - Space complexity:
O(1)— Space complexity for Brute Force (Built-in Comparison Sort).
Why Brute Force Doesn't Scale:
For huge arrays streamed or stored in cache lines, making multiple passes evicts cache lines. A one-pass partition guarantees minimal memory bus traffic and zero extra allocation.
With N = 10,000,000 values of categorical labels (e.g. Low, Medium, High priority packets in a network router), single-pass DNF partitions packets at line rate without buffering.