1. Subarray Copy and QuickSelect / Sorting
Intuition
For every incoming query:
1. Slice the subarray nums[L..R].
2. Sort the slice or use QuickSelect (nth_element) to locate the k-th smallest element.
3. Append to output.
For Q queries each covering up to N elements, overall runtime is O(Q \cdot (R - L + 1) log (R - L + 1)), leading to TLE for large inputs.
When to apply: When total number of queries is very small (Q <= 50).
Algorithm
- Step 1: Iterate through each query [L, R, k].
- Step 2: Copy nums[L..R] into a temporary vector.
- Step 3: Sort the temporary vector in ascending order.
- Step 4: Record element at index k - 1 into results.
- Step 5: Return all query results.
#include <iostream>#include <vector>#include <algorithm> std::vector<int> solveBruteForce(const std::vector<int>& nums, const std::vector<std::vector<int>>& queries) { std::vector<int> res; res.reserve(queries.size()); for (const auto& q : queries) { int l = q[0], r = q[1], k = q[2]; std::vector<int> sub(nums.begin() + l, nums.begin() + r + 1); std::sort(sub.begin(), sub.end()); res.push_back(sub[k - 1]); } return res;} int main() { std::vector<int> nums = {3, 2, 5, 8, 4, 3, 7, 2, 9}; std::vector<std::vector<int>> queries = {{1, 4, 2}, {0, 4, 3}, {2, 6, 1}}; auto ans = solveBruteForce(nums, queries); for (int x : ans) std::cout << x << " "; std::cout << std::endl; return 0;}Time & Space Complexity
- Time complexity:
O(Q * M log M) where M is average range length (R - L + 1) - Space complexity:
O(M) temporary storage per query