PROBLEM DESCRIPTION
Given a binary matrix your task is to find all unique rows of the given matrix in the order of their appearance in the matrix.
SOLUTION
For each row, we convert it into a string and check if it’s already in our set. If it’s not, we add it to our list of unique rows.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class GfG
{
public static ArrayList<ArrayList<Integer>> uniqueRow(int a[][],int r, int c)
{
ArrayList<ArrayList<Integer>> list = new ArrayList<>();
Set<String> set = new HashSet<>();
for(int i=0; i<r; i++){
ArrayList<Integer> temp = new ArrayList<>();
StringBuffer sb = new StringBuffer();
for(int j=0; j<c; j++){
sb.append(String.valueOf(a[i][j]));
temp.add(a[i][j]);
}
if(!set.contains(sb.toString())){
list.add(temp);
}
set.add(sb.toString());
}
return list;
}
}