Print unique rows in a boolean matrix

Easy

Problem

Print each distinct row of a binary matrix once, in order of first appearance.

Example 1

Input:  [[1,1,0,1], [1,0,0,1], [1,1,0,1]]
Output: 1 1 0 1, 1 0 0 1

Also asked as: Print unique rows in a given boolean matrix

Test cases

Case 1

Input:    [[1,1,0,1],[1,0,0,1],[1,1,0,1]]
Expected: [[1,1,0,1],[1,0,0,1]]

Case 2

Input:    [[0,0],[0,0],[0,0]]
Expected: [[0,0]]

Case 3

Input:    [[1,0],[0,1]]
Expected: [[1,0],[0,1]]

Case 4

Input:    [[1]]
Expected: [[1]]

Your solution ✓ Solved

Ctrl/⌘ + Enter to run
View solutionHide solution1 approach

1. Trie of rows (or a set of joined strings)

Time O(rows · cols)Space O(rows · cols)

Treat each row as a binary string; insert into a trie (or a Set). Print a row only the first time it is inserted.

function uniqueRows(matrix) {
const seen = new Set();
const out = [];
for (const row of matrix) {
const key = row.join('');
if (!seen.has(key)) { seen.add(key); out.push(row); }
}
return out;
}