Given a 2D space of maximum size NxN which supports two operations :
[1] void UPDATE(x,y,v) - sets the value of cell [x,y] to v
[2] int SUM(x1,y1,x2,y2) - returns sub-rectangle sum (x1,y1) to (x2,y2)
inclusive, and there is an infinite stream of such 2 types of operations which have to supported. How would you store the values for efficient updates and retrievals ?
SOLUTION
A. optimize for the case where updates are frequent - make update as fast as possible
Store the values in a 2D array - x and y are indexes into the array
To update O(1): array[x][y] = v
To sum O(n^2):
sum = 0
for (int x = x1; x <= x2; x++) {
for (int y = y1; y <= y2; y++ {
sum += array[x][y];
}
return sum;
B. To have the sum be O(1), store the sum of every element in (0,0) to (i,j) in arr[i][j]
1 3 6
5 12 21
12 27 45
SUM = arr[x2][x2] - arr[x1-1][y2] - arr[x2][y1-1] + arr[x1-1][y1-1]
UPDATE[i,j] only have to take care of everything on or after i,j in sum array