1. Direct Array Loops
Intuition
Store nums in a basic array.
- updateRange(L, R, val): For i from L to R, add val to nums[i]. Runs in O(n) time.
- queryRange(L, R): For i from L to R, sum elements nums[i]. Runs in O(n) time.
For Q operations, total time is O(Q \cdot n), which times out for large N and Q.
When to apply: Basic prototyping when N, Q <= 1000.
Algorithm
- Step 1: Store elements in array nums.
- Step 2: On updateRange(L, R, val), loop i from L to R adding val.
- Step 3: On queryRange(L, R), loop i from L to R adding nums[i] to a sum variable and return.
#include <iostream>#include <vector> class LazyBrute { std::vector<long long> arr;public: LazyBrute(const std::vector<int>& nums) : arr(nums.begin(), nums.end()) {} void updateRange(int l, int r, int val) { for (int i = l; i <= r; ++i) arr[i] += val; } long long queryRange(int l, int r) { long long sum = 0; for (int i = l; i <= r; ++i) sum += arr[i]; return sum; }}; int main() { std::vector<int> nums = {1, 2, 3, 4, 5}; LazyBrute st(nums); std::cout << st.queryRange(0, 4) << std::endl; st.updateRange(1, 3, 10); std::cout << st.queryRange(0, 4) << std::endl; std::cout << st.queryRange(1, 2) << std::endl; return 0;}Time & Space Complexity
- Time complexity:
O(n) per updateRange and queryRange - Space complexity:
O(n) space for array storage