1. Direct Query Processing
Intuition
For every query [L, R], run a standard loop from index L to R summing elements. While simple, processing each query takes O(n) time in the worst case, leading to O(q \cdot n) overall time complexity which times out for large query counts.
When to apply: Feasible only when the number of queries is tiny or array sizes are very small.
Algorithm
- Step 1: Allocate an answer list of size equal to the number of queries.
- Step 2: For each query [L, R], iterate i from L to R adding nums[i] to a local sum.
- Step 3: Store the computed sum at the query's index in the answer array.
- Step 4: Return the answers list after all queries are evaluated.
#include <iostream>#include <vector> std::vector<long long> solveBruteForce(const std::vector<int>& nums, const std::vector<std::pair<int, int>>& queries) { std::vector<long long> results; results.reserve(queries.size()); for (const auto& q : queries) { long long sum = 0; for (int i = q.first; i <= q.second; ++i) { sum += nums[i]; } results.push_back(sum); } return results;} int main() { std::vector<int> nums = {1, 1, 2, 1, 3, 4, 5, 2, 8}; std::vector<std::pair<int, int>> queries = {{0, 4}, {1, 3}, {2, 4}}; auto ans = solveBruteForce(nums, queries); for (size_t i = 0; i < ans.size(); ++i) { std::cout << ans[i] << (i + 1 == ans.size() ? "" : " "); } std::cout << std::endl; return 0;}Time & Space Complexity
- Time complexity:
O(q * n) where q is the number of queries and n is the array length - Space complexity:
O(1) auxiliary space (excluding result storage)