The key constraint is that the array is immutable and queries happen repeatedly, so preprocessing is the move.
Recognize that the array is immutable and queried many times, so preprocessing is ideal. Build a prefix sum array where each element stores the cumulative count of 1s up to that index. Then answer each query in O(1) time by subtracting prefix sums at the boundaries.
Pro tip: Mention that if the array is extremely large and memory is a concern, you could use a bit vector with rank/select operations, but prefix sum is simpler and usually sufficient. Also, clarify that inclusive indices mean you need to handle the lower bound carefully (e.g., if i=0, use 0 as the base).
Confirm that the array is immutable, queries are frequent, and indices are inclusive. Ask about memory constraints and expected query volume to decide on preprocessing.
Explain that you can precompute a prefix sum array where prefix[k] = number of 1s from index 0 to k. This takes O(n) time and O(n) space.
For query (i, j), the count is prefix[j] - (i > 0 ? prefix[i-1] : 0). This gives O(1) per query.
Discuss time-space trade-offs: prefix sum uses O(n) extra space. If memory is tight, consider a bit vector with rank/select (O(n) bits) but more complex. Also mention that if updates were allowed, a Fenwick tree would be needed.
Address edge cases: i=0, i=j, i>j (invalid), and all 0s or all 1s. Conclude that prefix sum is optimal for immutable, frequent queries.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.