Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in-place.
Input:
[
[1,1,1],
[1,0,1],
[1,1,1]
]
Output:
[
[1,0,1],
[0,0,0],
[1,0,1]
]
Input:
[
[0,1,2,0],
[3,4,5,2],
[1,3,1,5]
]
Output:
[
[0,0,0,0],
[0,4,5,0],
[0,3,1,0]
]
- A straight forward solution using O(mn) space is probably a bad idea.
- A simple improvement uses O(m + n) space, but still not the best solution.
- Could you devise a constant space solution?
-
Time complexity :
O(m * n). Wheremandnare the number of rows and columns respectively. Comparision operation costsO(1)time and we traverse the whole matrix once. -
Space complexity :
O(1). We only use two extra boolean variables in the solution. Everything else is donein-place.