Microsoft Interview Question
Software Engineer / DevelopersDenote M[i][j][0] and M[i][j][1] as the height and width of the largest block starting from (i,j). Then we have:
if A[i][j]=0, M[i][j][0]=M[i][j][1]=0, otherwise:
M[i][j][0] = min{M[i+1][j][0], M[i][j+1][0], M[i+1][j+1][0]} + 1;
M[i][j][1] = min{M[i+1][j][1], M[i][j+1][1], M[i+1][j+1][1]} + 1;
And we initialize the DP procedure by calculating the M's for the last column and last row.
(1) Construct a new n x n matrix m, whose elements m[i][j] = number of continuous 1 to the right. This matrix can be constructed in O(n^2) time.
(2) For each m[i][j], we find the longest continuous nonzero subarray started at m[i][j] within the i-th column. The length of this subarray and the minimum of this subarray is the height and the width of the continuous block of 1 started at (i,j). This step can be done in O(n^2) too.
(3) Switch the role of row and column and repeat (1) and (2). This step is needed because the steps(1) and (2) will find the blocks along the vertical direction first. For instance, lets consider
1 1 1
1 0 0
0 0 0
the steps (1)-(2) will return the (1,1) pattern along the vertical direction for the (0,0) element.
Kadane's 2D algorithm definitely solves in O(n^3) time. However, here is another O(n^3) solution:
for (i = 0; i < n; i++)
{
array[n] <- m[i];
for (j = i + 1; j < n; j++)
{
array[n] <- array[n] & m[j]
foreach contiguous 1's
{
number of ones <- (j - i) * number_of_contiguous_ones;
if (number_of_contiguous_ones > max)
max <- number_of_contiguous_ones
}
}
}
any ideas? dynamic programming?
- Ramu September 09, 2007