14 · Hashing & Prefix Sums

#304 Range Sum Query 2D - Immutable

Mediumsolve on LeetCode ↗

frequently reported atGoogleAmazonMeta

the problem

In plain words

Design a class built from a matrix that answers many sumRegion(row1, col1, row2, col2) queries: the sum inside that rectangle, inclusive. Each query must be O(1).

in matrix = [[3,0,1,4,2],[5,6,3,2,1],[1,2,0,1,5],[4,1,0,1,7],[1,0,3,0,5]]; sumRegion(2,1,4,3), sumRegion(1,1,2,2), sumRegion(1,2,2,4)

out 8, 11, 12

  • 1 ≤ rows, cols ≤ 200
  • -10⁴ ≤ matrix[i][j] ≤ 10⁴
  • Up to 10⁴ queries

your turn

Try it before you peek

Read the examples, say the brute force out loud, then write code: here or on LeetCode ↗. Stuck for 20 minutes? Open one hint at a time.

Solve it in the browser

Design: implement every operation. Compiled by the real javac (Java 17) and judged right here — nothing is sent anywhere.

    Solutions are hidden so you can try first. Even 20 minutes of real effort makes the answer stick far better than reading it.

    Marking the problem solved, or opening every hint, also shows it.

    practise next

    Similar problems

    1. #303
    2. #307
      Range Sum Query - Mutable
      Mediumin Range Queries & Strings