A range query library
The problem
Build a small C++ program that answers many questions about an array quickly: range sums, range additions, best windows and the number of subarrays with a given sum, and show that each is fast on a big input.
Requirements
- Answer range sums with a prefix-sum array
- Apply many range additions with a difference array
- Find the best window of size k and the shortest segment with a given sum using two pointers
- Count subarrays with a given sum when numbers can be negative
Technologies
- C++17
- vector and long long
- sort and lower_bound
- Prefix sums and two pointers
Step by step
- Read the array and the queries with fast input.
- Build the prefix-sum array and answer the range-sum queries.
- Apply the range additions with a difference array and rebuild the array.
- Add the window and subarray-count functions and test each against a slow brute force on small inputs.
Expected result
A program that answers 10⁵ queries on an array of 10⁵ numbers in well under a second, with tests that compare it to simple slow code.
How it is evaluated
- Every answer matches the brute force on random small inputs
- Each operation has the complexity the lesson describes
- long long is used wherever sums can be large
- The code reads the input exactly as specified
Ways to improve it
- Add a 2D prefix sum for rectangle sums
- Time the fast and slow versions on a large input
- Handle several test cases in one run