LeetCode 304. - Range Sum Query 2D - Immutable [Algorithm + Code Explained ]

preview_player
Показать описание
One of the most frequently asked coding interview questions on Dynamic Programming in companies like Google, Facebook, Amazon, LinkedIn, Microsoft, Uber, Apple, Adobe etc.

LeetCode : Range Sum Query 2D - Immutable

Question : Given a 2D matrix matrix, find the sum of the elements inside the rectangle defined by its upper left corner (row1, col1) and lower right corner (row2, col2).

Range Sum Query 2D
The above rectangle (with the red border) is defined by (row1, col1) = (2, 1) and (row2, col2) = (4, 3), which contains sum = 8.

Example:
Given 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) - 8
sumRegion(1, 1, 2, 2) - 11
sumRegion(1, 2, 2, 4) - 12
Note:
You may assume that the matrix does not change.
There are many calls to sumRegion function.
You may assume that row1 ≤ row2 and col1 ≤ col2.

Рекомендации по теме
Комментарии
Автор

This is by far the clearest explanation I've come across! Thanks!!!

For those that are wondering, the dp matrix for the first example ends up looking like this:

[0, 0, 0, 0, 0, 0]
[0, 3, 3, 4, 8, 10]
[0, 8, 14, 18, 24, 27]
[0, 9, 17, 21, 28, 36]
[0, 13, 22, 26, 34, 49]
[0, 14, 23, 30, 38, 58]

So when calling sumRegion(2, 1, 4, 3), it returns 38 - 14 - 24 + 8 = 8

WdnUlikno
Автор

It'll be great if you can show how the DP matrix will look like. Thanks for the explanation

gulshansingh
Автор

Great 👍. Hope to see more solutions especially for dynamic programming.

nagarjunareddypadala
Автор

Great explanation!!!
Suscribed ...keep making videos.

Igloo
Автор

Please briefly explain the question 🙄.

VISHALSHARMA-mukl
visit shbcf.ru