Member-only story

Leetcode 1476: Subrectangle Queries

Pierre-Marie Poitevin
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).

Problem statment

Solution

A couple of simple ideas for the solution:

  1. 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.
  2. 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 :)

--

--

Pierre-Marie Poitevin
Pierre-Marie Poitevin

No responses yet