1. Pairwise Row Equality Comparison
Intuition
Loop through each row i. Compare against all previous rows j < i. If M[i] == M[j] for all columns, row is duplicate. Otherwise add to output.
When to apply: Basic baseline check.
Algorithm
- Step 1: Initialize
result = []. - Step 2: Loop
ifrom 0 to row - 1. - Step 3: Check if row
iequals any rowj < i. - Step 4: If not seen, append row
itoresult. - Step 5: Return
result.
#include <iostream>#include <vector>using namespace std; class Solution {public: vector<vector<int>> uniqueRow(int M[1000][1000], int row, int col) { vector<vector<int>> result; for (int i = 0; i < row; i++) { bool isDuplicate = false; for (int j = 0; j < i; j++) { bool match = true; for (int k = 0; k < col; k++) { if (M[i][k] != M[j][k]) { match = false; break; } } if (match) { isDuplicate = true; break; } } if (!isDuplicate) { vector<int> r(col); for (int k = 0; k < col; k++) r[k] = M[i][k]; result.push_back(r); } } return result; }}; int main() { Solution sol; int M[1000][1000] = {{1, 1, 0, 1}, {1, 0, 0, 1}, {1, 1, 0, 1}}; auto res = sol.uniqueRow(M, 3, 4); for (const auto& r : res) { for (int v : r) cout << v << " "; cout << endl; } return 0;}Time & Space Complexity
- Time complexity:
O(row^2 * col)— Checks all O(row2) pairs of rows with O(col) element comparisons each. - Space complexity:
O(1)— No extra data structures allocated.
Why Brute Force Doesn't Scale:
Pairwise row checks fail on large matrices due to quadratic row scaling.
Binary Trie runs in 1,000,000 pointer transitions, executing in less than 15ms.