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:
- Take the first column, go through it, if see zero, jump on the next column and so on. But the worst case of this algorithm will be O(n2);
- The next one, if I will have a sum of all columns than I can give an answer in O(n). But it's not said at task conditions that we have computed sums. And if I will compute them, the complexity will be also O(n2);
Any other solutions?
What is the input for the matrix?
If you get a number for each column, i.e. in your example (in decimal) 14, 8, 4, 31, 1, you could just create a number
a
withn
binary digits set to 1 (in this case 31). If this number is equal to one of the column numbers, one of the columns is all 1s.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.
* Also assuming that
n
is the matrix dimension here, not the total number of elements.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.
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 isO(n^2)
only.But my wild guess is that you doing a classic celebrity identification problem, and that you misunderstood the problem.
I celebrity identification problem, you are trying to find something like:
And indeed with this extra constrain on what you are trying to find, there is an
O(n)
solution.My solution is that we first assume that all columns have 1s, then we go row by row, over the possible solutions we still have, and cut columns that cannot be a solution.
This solution is written in Java:
Solution 1: O(n^2) straight-forward
Solution 2: O(n) using a customized data-structure