Member-only story
Leetcode 1476: Subrectangle Queries
1 min readJun 15, 2020
In this Leetcode problem, we need to implement a class maintaining and returning integer values in a rectangle (bi-dimensional array).
Solution
A couple of simple ideas for the solution:
- For each
update
query, set the new value to all the cells in the sub rectangle. Update doesn’t need to be atomic or thread safe. - For each
getValue
query, return the current value in the rectangle.
Here is the full code:
class SubrectangleQueries {
int[][] rectangle; public SubrectangleQueries(int[][] rectangle) {
this.rectangle = rectangle;
}
public void updateSubrectangle(
int row1, int col1, int row2, int col2, int newValue) {
for (int i = row1; i <= row2; i++) {
for (int j = col1; j <= col2; j++) {
rectangle[i][j] = newValue;
}
}
}
public int getValue(int row, int col) {
return rectangle[row][col];
}
}
Happy coding :)
What’s next:
- Checkout the solution for another problem: Rearrange words in a sentence
- Contact me: poitevinpm@gmail.com
- Looking to interview for a software engineer position? Contact me :)