1. Square All Elements & Comparison Sort
Intuition
Square every number in the array, then apply standard comparison sort in O(N log N) time.
Algorithm
- 1. For each element x in nums: replace x with x * x.
- 2. Sort the squared array using standard library sort.
- 3. Return the sorted array in O(N log N) time.
Square All Elements & Comparison Sort
2 of 2 questions left todayPhase 1 — Square Each Element: Iterate over nums and compute square: (-4)^2 = 16, (-1)^2 = 1, 0^2 = 0, 3^2 = 9, 10^2 = 100
Phase 1 — Square Each Element: Iterate over nums and compute square: (-4)^2 = 16, (-1)^2 = 1, 02 = 0, 32 = 9, 102 = 100.
#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> sortedSquares(vector<int>& nums) { for (int& x : nums) x = x * x; sort(nums.begin(), nums.end()); return nums; }}; int main() { Solution sol; vector<int> nums = {-4, -1, 0, 3, 10}; vector<int> res = sol.sortedSquares(nums); cout << "Sorted Squares: ["; for (size_t i = 0; i < res.size(); ++i) { cout << res[i] << (i + 1 < res.size() ? ", " : ""); } cout << "]" << endl; return 0;}Time & Space Complexity
- Time complexity:
O(N log N)— Squaring takes O(N) and comparison sorting takes O(N log N). - Space complexity:
O(1)— In-place sort takes 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.