Coding problem
Sums of any range, answered fast
The task
A sales report lets a manager ask for the total between any two days, and the same report is asked thousands of times a minute.
Complete the class RangeSums. Its constructor gets the daily values once. Sum(left, right) returns the sum of the values from index left to index right, both included, where 0 ≤ left ≤ right < values.Length. Answers use the values as they were when the object was built, even if the caller changes the array later. A sum can be larger than an int, so Sum returns a long.
Signature
public sealed class RangeSums public RangeSums(int[] values) public long Sum(int left, int right)
Examples
- values
[3, -2, 5, 1], thenSum(0, 3)→7. 3 − 2 + 5 + 1. - values
[3, -2, 5, 1], thenSum(1, 2)→3. −2 + 5.
Limits: Up to 400,000 values and 400,000 calls of Sum.
The tests check: one-value ranges at both ends, a negative value, a one-value array, three int.MaxValue values (a sum beyond int), a change to the caller's array after the object is built, and 400,000 calls in time.
Hints
Your code
Already included: using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Http; using System.Threading; using System.Threading.Tasks;
public sealed class RangeSums
{
public RangeSums(int[] values)
{
throw new NotImplementedException();
}
// Returns values[left] + ... + values[right], both included.
public long Sum(int left, int right)
{
throw new NotImplementedException();
}
}This problem comes with TechInterviewNotes Full Access
Unlock all paid content on TechInterviewNotes.