Print unique rows in a given boolean matrix
Pattern: Insert, search and prefix
Insert each row into a binary trie (two children per node). A row that creates at least one new node has not been seen before, so it is printed; a row that walks only existing nodes is a repeat.
No verified practice link yet. The guide below states the problem in full, so you can still solve it here.
The problem
Given a binary matrix, return its distinct rows in the order they first appear. The catalogue has no practice link for this one.
Think first
- How can a row be stored so equal rows share storage?
- How do you know a row is new?
- What else would work?
Hints
Brute force, and why it fails
Compare each row with every earlier row: O(R² × C).
The key insight
Equal rows follow the same trie path, so a new node appears exactly for new rows.
Dry run
Row 1101: new path, printed.
Step 1 of 2
The plan
for each row: walk the binary trie, creating nodes; if any node was created: output the row
Complexity
- Time
O(R × C)- Space
O(R × C)
Each cell is one step.
Edge cases
- All rows equal: one row.
- One column.
- All distinct.
I've built my logic, show the code
Java
import java.util.*;
class Solution {
public int[][] uniqueRow(int[][] M) {
int cols = M[0].length;
int[][] next = new int[M.length * cols + 1][2]; // a binary trie: next[node][bit], 0 = none
int nodes = 1;
List<int[]> out = new ArrayList<>();
for (int[] row : M) {
int n = 0;
boolean isNew = false;
for (int b : row) {
if (next[n][b] == 0) { next[n][b] = nodes++; isNew = true; } // a new node means a row not seen before
n = next[n][b];
}
if (isNew) out.add(row);
}
return out.toArray(new int[0][]);
}
}C++
class Solution {
public:
vector<vector<int>> uniqueRow(vector<vector<int>>& M) {
vector<vector<int>> next(1, vector<int>(2, 0)); // a binary trie: next[node][bit], 0 = none
vector<vector<int>> out;
for (const vector<int>& row : M) {
int n = 0;
bool isNew = false;
for (int b : row) {
if (next[n][b] == 0) { // a new node means a row not seen before
next[n][b] = static_cast<int>(next.size());
next.push_back(vector<int>(2, 0));
isNew = true;
}
n = next[n][b];
}
if (isNew) out.push_back(row);
}
return out;
}
};Python
class Solution:
def uniqueRow(self, M: list[list[int]]) -> list[list[int]]:
root, out = {}, [] # a binary trie of the rows seen so far
for row in M:
node, is_new = root, False
for b in row:
if b not in node: # a new node means a row not seen before
node[b] = {}
is_new = True
node = node[b]
if is_new:
out.append(row)
return outCommon mistakes
- Printing in sorted order instead of first appearance.
- Marking only the last node, which works too but needs an end flag.