1. Nested Loops
Intuition
Iterate through each index i from 0 to n - 1. For each i, inner loop through all j > i and increment a counter whenever nums[j] < nums[i]. While trivial to implement, testing all pairs takes O(n2) time, causing TLE when n = 105.
When to apply: Constraint sizes where n <= 1000.
Algorithm
- Step 1: Allocate counts array of length n initialized to 0.
- Step 2: Loop i from 0 to n - 1.
- Step 3: Loop j from i + 1 to n - 1.
- Step 4: If nums[j] < nums[i], increment counts[i].
- Step 5: Return counts.
#include <iostream>#include <vector> std::vector<int> countSmallerBrute(const std::vector<int>& nums) { int n = nums.size(); std::vector<int> counts(n, 0); for (int i = 0; i < n; ++i) { for (int j = i + 1; j < n; ++j) { if (nums[j] < nums[i]) { counts[i]++; } } } return counts;} int main() { std::vector<int> nums = {5, 2, 6, 1}; auto res = countSmallerBrute(nums); for (int x : res) std::cout << x << " "; std::cout << std::endl; return 0;}Time & Space Complexity
- Time complexity:
O(n^2) where n is nums length - Space complexity:
O(1) auxiliary space (excluding result array)