1. Brute Force — Linear Iteration per Query
Intuition
Store the array as is. For each sumRange(left, right) call, loop from left to right and compute the sum on demand.
Algorithm
- Constructor: store reference to
nums. - sumRange(left, right):
-
sum = 0. - Loop
ifromlefttoright: -
sum += nums[i]. - Return
sum.
Per-Query Linear Iteration (O(N) per Query)
2 of 2 questions left todayRead first element in range
Read first element in range.
#include <iostream>#include <vector>using namespace std; // Brute Force: O(N) per queryclass NumArray { vector<int> nums;public: NumArray(vector<int>& nums) : nums(nums) {} int sumRange(int left, int right) { int sum = 0; for (int i = left; i <= right; i++) { sum += nums[i]; } return sum; }}; int main() { vector<int> nums = {-2, 0, 3, -5, 2, -1}; NumArray numArray(nums); cout << "sumRange(0, 2): " << numArray.sumRange(0, 2) << endl; cout << "sumRange(2, 5): " << numArray.sumRange(2, 5) << endl; cout << "sumRange(0, 5): " << numArray.sumRange(0, 5) << endl; return 0;}Time & Space Complexity
- Time complexity:
O(N^2)— Time complexity for Approach 1: Brute Force — Linear Iteration per Query. - Space complexity:
O(1)— Space complexity for Approach 1: Brute Force — Linear Iteration per Query.
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.