1. Standard Comparison Sort
Intuition
Sort the input array using standard comparison sort in O(N log N) time.
Algorithm
- 1. Call built-in comparison sorting algorithm on the array.
- 2. Orders elements in O(N log N) time without exploiting bounded integer ranges.
Standard Comparison Sort (O(N log N))
2 of 2 questions left todayPhase 1 — Initial Unsorted Array: nums = [4, 2, 2, 8, 3, 3, 1]
Phase 1 — Initial Unsorted Array: nums = [4, 2, 2, 8, 3, 3, 1]. Length = 7. Standard quicksort/mergesort makes pairwise comparisons.
#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: vector<int> countSort(vector<int>& arr) { std::sort(arr.begin(), arr.end()); return arr; }}; int main() { Solution sol; vector<int> nums = {4, 2, 2, 8, 3, 3, 1}; vector<int> sorted = sol.countingSort(nums); cout << "Counting Sort: ["; for (size_t i = 0; i < sorted.size(); ++i) { cout << sorted[i] << (i + 1 < sorted.size() ? ", " : ""); } cout << "]" << endl; return 0;}Time & Space Complexity
- Time complexity:
O(N log N)— Standard comparison sorting performs O(N log N) operations. - Space complexity:
O(1)— In-place comparison sorting uses 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.