Input:
[1, 0, 1],
[0, 1, 0],
[1, 0, 1]
Output: [2, 1, 2]
For this example, n = number of rows or columns
For the given binary matrix, can I get an array of the count of 1's in each row in O(n) time complexity?
Input:
[1, 0, 1],
[0, 1, 0],
[1, 0, 1]
Output: [2, 1, 2]
For this example, n = number of rows or columns
For the given binary matrix, can I get an array of the count of 1's in each row in O(n) time complexity?
If N
is the number of rows, then there is no O(N)
solution. You need to visit each cell. There are N^2
cells so the complexity is O(N^2)
.
If you represent the matrix using bits (0 or 1) rather than integer counts, you can do the bit counting faster than iterating the bits. However, there are still O(N^2)
bits in the matrix. Even if you pack them 32 or 64 bits per word, you still have O(N^2)
words to visit... so the complexity remains the same.