1561. Minimal Key Columns
A lab keeps a sheet of grid readings: each row is one specimen and each column is a yes/no test (1 = positive). To save money the lab wants to run only a few of the tests, yet the chosen tests alone must still tell every pair of specimens apart, meaning any two rows differ in at least one chosen column.
Return the smallest number of columns that achieves this. If two rows are completely identical no choice can separate them, so return -1. If there is only a single row nothing needs separating, so return 0.
Hint for the intended solution: treat each row as a bitmask over the columns, mark the difference mask of every pair of rows, spread those marks to all supermasks with one sum-over-subsets pass, and pick the cheapest column set whose complement is unmarked. Target time O(rows^2 + cols * 2^cols) and space O(2^cols).
Example 1
- Input:
- grid = [[0,1],[1,0]]
- Output:
- 1
- Explanation:
The two specimens differ in every test, so a single column already separates them.
Example 2
- Input:
- grid = [[1,1],[1,1]]
- Output:
- -1
- Explanation:
The rows are identical, so no set of columns can separate them.
Example 3
- Input:
- grid = [[0,0,0],[0,1,1],[1,0,1],[1,1,0]]
- Output:
- 2
- Explanation:
No single column works, but columns 0 and 1 together give four different patterns.
Constraints
1 ≤ rows ≤ 60; 1 ≤ cols ≤ 16; rows * cols ≤ 1000; grid[i][j] in {0, 1}
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
- Time per case
- Python 1,200 msC++ 300 msJava 600 msJavaScript 600 msTypeScript 600 ms
Expected complexity
- Time
- O(rows^2 + cols * 2^cols)
- Space
- O(2^cols)