Range Sum Query – Immutable
Problem Statement
You are given an integer array nums that never changes. After that, you will be asked many questions of the form "what is the sum of nums[left] through nums[right], both ends included?"
Write a class NumArray:
NumArray(vector<int>& nums)receives the array once.int sumRange(int left, int right)returnsnums[left] + nums[left + 1] + … + nums[right].
The array nums (given once, to the constructor), followed by many calls sumRange(left, right).
For each sumRange call, the sum of the elements from index left to index right, inclusive.
(-2) + 0 + 3 = 1. 3 + (-5) + 2 + (-1) = -1. The whole array adds up to -3.
- • 1 ≤ nums.length ≤ 10^4
- • −10^5 ≤ nums[i] ≤ 10^5
- • 0 ≤ left ≤ right < nums.length
- • At most 10^4 calls to sumRange
- • Every total is at most 10^4 · 10^5 = 10^9 in size, so `int` is enough.
Pattern Recognition Clues
Recognising these key signals in the problem description immediately identifies the pattern:
Approach Complexity Ladder
Keep the array; each query adds nums[left..right] one by one
Build prefix of size n+1 once; each query is prefix[r+1] − prefix[l]
Store the array as it is. For each query, loop from left to right and add up the elements.
Recognition rule for this sub-pattern:
Unlock Complete Visual Walkthrough & Optimal C++
The interactive animated dry-run player, optimized C++ implementation, state invariant derivations, and edge-case breakdown for this question are part of Brute2Best Pro. The anchor question of every sub-pattern is completely free.
First anchor question per pattern, Part 1 LLD & Module 1 C++ basics are 100% Free forever.
How this concept connects to System Design & C++ Systems
Top engineering interviews test whether you understand how algorithms like Prefix Sum translate into production architectures and low-level memory mechanics.
Foundations: Object-Oriented Principles in C++23
Class invariants, pure virtual interfaces, and RAII smart pointers.
Food Delivery System (Zomato Architecture)
Real-world machine coding application of algorithms and design patterns.
Pointers vs References Deep Dive
Pointer arithmetic and memory layout under the hood.
Virtual Method Table (vtable) & Memory Layout
Polymorphism, vptr overhead, and multiple inheritance in memory.