Engineering platform~30 min2s · 256 MBtarget O(R × C) time, O(C) spaceclassic twin: lc-221dp
An internal desk-booking tool for an engineering team shows the office floor as a grid. A . is a free desk and a # is a desk that is taken. A team that sits together needs a square block of free desks, with the same number of rows and columns.
Your team lead asks: "How many desks are in the largest square block that is entirely free?"
Write largest_free_square(desks).
desks is a list of equal-length strings. . is a free desk and # is a taken desk.Input: desks = ["..#.", "....", ".#..", "...."]
Output: 4Let side[r][c] be the side of the largest free square whose bottom right desk is (r, c). A taken desk gives 0. A free desk on the first row or first column gives 1. Any other free desk gives one more than the smallest of the three neighbours above, to the left, and diagonally up and to the left.
Why the smallest? A square of side k ending here needs squares of side k - 1 ending at all three neighbours. The smallest neighbour limits the side.
| Row | Column 0 | Column 1 | Column 2 | Column 3 |
|---|---|---|---|---|
| 0 | 1 | 1 | 0 (taken) | 1 |
| 1 | 1 | 2 | 1 | 1 |
| 2 | 1 | 0 (taken) | 1 | 2 |
| 3 | 1 | 1 | 1 | 2 |
The largest side is 2, so the answer is 2 × 2 = 4.
Input: desks = ["##", "##"]
Output: 0Every desk is taken, so there is no free block: 0.
Input: desks = ["...", "..."]
Output: 4The floor is 2 rows by 3 columns, so the largest square has side 2: 4 desks.
1 ≤ rows ≤ 500 and 1 ≤ cols ≤ 500, and every string has the same length.. or #.A floor of 500 by 500 desks has 250,000 desks. Checking every square at every desk costs more than 10 to the power 10 steps. A table with one entry for each desk, each read from three neighbours, takes about 750,000 small steps.