I have a matrix which looks like this:
| 1 | 0 | 0 | 1 | 0 |
| 1 | 1 | 0 | 1 | 0 |
| 1 | 0 | 1 | 1 | 0 |
| 1 | 0 | 0 | 1 | 0 |
| 0 | 0 | 0 | 1 | 1 |
I should find if this matrix has a column filled with all 1. At this matrix it's column 4. And it's said that time complexity is O(n) and memory is O(1).
This matrix represents a binary relation on a set (of people). n
is the size of the set, so the size of the matrix is n * n
.
I can see 2 possible solutions:
Any other solutions?
Assuming arbitrary content, you cannot avoid a worst-case of O(n2).* You have to visit every element in each column that you want to consider, and in the worst-case, you have to consider all columns.
n
is the matrix dimension here, not the total number of elements.
Let me take a very wild guess on what you are trying to do. Hint from the mention of:
O(n)
algorithmWell, you can not do that in O(n)
and I can prove that it is O(n^2)
only.
But my wild guess is that you doing a classic celebrity identification problem, and that you misunderstood the problem.
A celebrity is person that is known by every other person, but doesn't know any [other people].
I celebrity identification problem, you are trying to find something like:
Find the number i where
a[i][x] = 1 for all x -> every one knows the celebrity
a[x][i] = 0 for all x != i -> the celebrity doesn't know anyone else
And indeed with this extra constrain on what you are trying to find, there is an O(n)
solution.
If you don't assume arbitrary content (as in Oli's answer) and you can encode each row as an unsigned integer with binary flags, then you can do it in O(n) and O(1) by just repeatedely performing a logical AND
of each row with the latest result.
The final set of flags will only have ones where the relevant column was also one.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With