Given a 2D Boolean matrix consisting of 0s and 1s. Find the largest size rectangle having all four borders as 1. The interior of it may or may not be entirely filled with 1s . I can think of O(n^4) solution . How can we improve it ?
# | User | Rating |
---|---|---|
1 | tourist | 3993 |
2 | jiangly | 3743 |
3 | orzdevinwang | 3707 |
4 | Radewoosh | 3627 |
5 | jqdai0815 | 3620 |
6 | Benq | 3564 |
7 | Kevin114514 | 3443 |
8 | ksun48 | 3434 |
9 | Rewinding | 3397 |
10 | Um_nik | 3396 |
# | User | Contrib. |
---|---|---|
1 | cry | 167 |
2 | Um_nik | 163 |
3 | maomao90 | 162 |
3 | atcoder_official | 162 |
5 | adamant | 159 |
6 | -is-this-fft- | 158 |
7 | awoo | 156 |
8 | TheScrasse | 154 |
9 | Dominater069 | 153 |
10 | nor | 152 |
Given a 2D Boolean matrix consisting of 0s and 1s. Find the largest size rectangle having all four borders as 1. The interior of it may or may not be entirely filled with 1s . I can think of O(n^4) solution . How can we improve it ?
Name |
---|
Hi, do you have the source of the problem?
Recently i attended amazon-india interview. They asked me this question .
There is an O(n3) solution. First, calculate the partial sums for all rows: for column i this array is rowSum[i][]. Then we iterate over the rows, r. In array upperSide[i][j] we will store the highest row k such that from index i till j inclusive there are only 1's in row k, and in columns i and j from indices k till r inclusive are only 1's; or -1, if there is no such row. In each row iteration, r, we check for the pair of indices i, j, whether in this row from i to j inclusive there are only 1's (we do this in constant time with partial sums). If yes, then we check if upperSide[i][j] is not -1, and update the answer with this rectangle; if in this case upperSide[i][j] is -1, we update upperSide[i][j] with r. Last, if at positions i and j in this row r is at least one 0, we update upperSide[i][j] with -1.