Count of unique rows in a given Matrix
Last Updated :
25 Mar, 2023
Given a 2D matrix arr of size N*M containing lowercase English letters, the task is to find the number of unique rows in the given matrix.
Examples:
Input: arr[][]= { {‘a’, ‘b’, ‘c’, ‘d’},
{‘a’, ‘e’, ‘f’, ‘r’},
{‘a’, ‘b’, ‘c’, ‘d’},
{‘z’, ‘c’, ‘e’, ‘f’} }
Output: 2
Explanation: The 2nd and the 4th row are unique.
Input: arr[][]={{‘a’, ‘c’},
{‘b’, ‘d’},
{‘e’, ‘f’}}
Output: 3
Naive Approach: Traverse all rows one by one and for each row check if it is unique or not by comparing it with all the other rows.
Step-by-step algorithm for implementing the approach
1) Firstly, start the program and include necessary header files.
2) Define a function isUniqueRow() that takes a 2D character vector arr and an integer row as input parameters, and returns a boolean value. Now follow the below steps:
- For i from 0 to row-1 do the following:
a. Set flag to true
b. For j from 0 to the number of columns in arr[0] do the following:
b.a. If arr[i][j] is not equal to arr[row][j], set flag to false and break the loop
c. If flag is true, return false
- Return true
3) Now, define another function countUniqueRows() that takes a 2D character vector arr as input parameter and returns an integer value.
- Initialize count to 0
- For i from 0 to the number of rows in arr do the following:
a. If isUniqueRow(arr, i) is true, increment count
- Return count
4) Now wecall the isUniqueRow() function for each row of arr and increment the count variable if the returned value is true, and also return the final value of count after completing the loop.
5) Call the countUniqueRows() function with the test data arr and output the result to the console.
6) End the program.
C++
#include <bits/stdc++.h>
using namespace std;
bool isUniqueRow(vector<vector< char >> arr, int row)
{
for ( int i=0; i<row; i++)
{
bool flag = true ;
for ( int j=0; j<arr[0].size(); j++)
{
if (arr[i][j] != arr[row][j])
{
flag = false ;
break ;
}
}
if (flag)
return false ;
}
return true ;
}
int countUniqueRows(vector<vector< char >> arr)
{
int count = 0;
for ( int i=0; i<arr.size(); i++)
{
if (isUniqueRow(arr, i))
count++;
}
return count;
}
int main()
{
vector<vector< char >> arr = {
{ 'a' , 'b' , 'c' , 'd' },
{ 'a' , 'e' , 'f' , 'r' },
{ 'a' , 'b' , 'c' , 'd' },
{ 'z' , 'c' , 'e' , 'f' },
};
cout << "Number of unique rows: " << countUniqueRows(arr) << endl;
return 0;
}
|
Python3
def isUniqueRow(arr, row):
for i in range (row):
if arr[i] = = arr[row]:
return False
return True
def countUniqueRows(arr):
count = 0
for i in range ( len (arr)):
if isUniqueRow(arr, i):
count + = 1
return count
if __name__ = = "__main__" :
arr = [
[ 'a' , 'b' , 'c' , 'd' ],
[ 'a' , 'e' , 'f' , 'r' ],
[ 'a' , 'b' , 'c' , 'd' ],
[ 'z' , 'c' , 'e' , 'f' ],
]
print ( "Number of unique rows: " , countUniqueRows(arr))
|
Javascript
function isUniqueRow(arr, row) {
for (let i = 0; i < row; i++) {
let flag = true ;
for (let j = 0; j < arr[0].length; j++) {
if (arr[i][j] !== arr[row][j]) {
flag = false ;
break ;
}
}
if (flag) {
return false ;
}
}
return true ;
}
function countUniqueRows(arr) {
let count = 0;
for (let i = 0; i < arr.length; i++) {
if (isUniqueRow(arr, i)) {
count++;
}
}
return count;
}
const arr = [
[ 'a' , 'b' , 'c' , 'd' ],
[ 'a' , 'e' , 'f' , 'r' ],
[ 'a' , 'b' , 'c' , 'd' ],
[ 'z' , 'c' , 'e' , 'f' ],
];
console.log( 'Number of unique rows: ' + countUniqueRows(arr));
|
Java
import java.util.Arrays;
class UniqueRows {
static boolean isUniqueRow( char [][] arr, int row)
{
for ( int i = 0 ; i < row; i++) {
if (Arrays.equals(arr[i], arr[row])) {
return false ;
}
}
return true ;
}
static int countUniqueRows( char [][] arr)
{
int count = 0 ;
for ( int i = 0 ; i < arr.length; i++) {
if (isUniqueRow(arr, i)) {
count++;
}
}
return count;
}
public static void main(String[] args)
{
char [][] arr = { { 'a' , 'b' , 'c' , 'd' },
{ 'a' , 'e' , 'f' , 'r' },
{ 'a' , 'b' , 'c' , 'd' },
{ 'z' , 'c' , 'e' , 'f' } };
System.out.println( "Number of unique rows: "
+ countUniqueRows(arr));
}
}
|
C#
using System;
using System.Collections.Generic;
public class Gfg
{
public static bool isUniqueRow(List<List< char >> arr, int row)
{
for ( int i = 0; i < row; i++)
{
bool flag = true ;
for ( int j = 0; j < arr[0].Count; j++)
{
if (arr[i][j] != arr[row][j])
{
flag = false ;
break ;
}
}
if (flag)
return false ;
}
return true ;
}
public static int countUniqueRows(List<List< char >> arr)
{
int count = 0;
for ( int i = 0; i < arr.Count; i++)
{
if (isUniqueRow(arr, i))
count++;
}
return count;
}
public static void Main()
{
List<List< char >> arr = new List<List< char >> {
new List< char >{ 'a' , 'b' , 'c' , 'd' },
new List< char >{ 'a' , 'e' , 'f' , 'r' },
new List< char >{ 'a' , 'b' , 'c' , 'd' },
new List< char >{ 'z' , 'c' , 'e' , 'f' }
};
Console.WriteLine( "Number of unique rows: " + countUniqueRows(arr));
}
}
|
Output
Number of unique rows: 3
Time complexity: O(N2 X M) where n is the number of rows and m is the number of columns in the input matrix. This is because the isUniqueRow function has a nested loop that compares each row with every other row before it.
Auxiliary Space: O(1) This is because the isUniqueRow() function uses constant space for its local variables and The countUniqueRows() function uses an integer variable count and calls the isUniqueRow() function, so its space complexity depends on the space complexity of isUniqueRow().
Efficient Approach: Using Hashing, we can store the key as a string containing all the characters in that row and its frequency as the value. And traverse all the rows in the map and if its frequency is 1 then count it as unique.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int uniqueRows(vector<vector< char > > arr)
{
unordered_map<string, int > mp;
string t;
for ( auto x : arr) {
t = "" ;
for ( auto y : x) {
t += y;
}
mp[t] += 1;
}
int cnt = 0;
for ( auto x : mp) {
if (x.second == 1) {
cnt += 1;
}
}
return cnt;
}
int main()
{
vector<vector< char > > arr = {
{ 'a' , 'b' , 'c' , 'd' },
{ 'a' , 'e' , 'f' , 'r' },
{ 'a' , 'b' , 'c' , 'd' },
{ 'z' , 'c' , 'e' , 'f' },
};
cout << uniqueRows(arr);
return 0;
}
|
Java
import java.util.*;
class GFG{
static int uniqueRows( char [][] arr)
{
HashMap<String, Integer> mp = new HashMap<>();
String t= "" ;
for ( char []x : arr) {
t = "" ;
for ( char y : x) {
t += y;
}
if (mp.containsKey(t)) {
mp.put(t, mp.get(t)+ 1 );
}
else
mp.put(t, 1 );
}
int cnt = 0 ;
for (Map.Entry<String,Integer> x : mp.entrySet()) {
if (x.getValue() == 1 ) {
cnt += 1 ;
}
}
return cnt;
}
public static void main(String[] args)
{
char [][] arr = {
{ 'a' , 'b' , 'c' , 'd' },
{ 'a' , 'e' , 'f' , 'r' },
{ 'a' , 'b' , 'c' , 'd' },
{ 'z' , 'c' , 'e' , 'f' },
};
System.out.print(uniqueRows(arr));
}
}
|
Python3
from collections import defaultdict
def uniqueRows(arr):
mp = defaultdict( int )
t = ""
for x in arr:
t = ""
for y in x:
t + = y
mp[t] + = 1
cnt = 0
for x in mp:
if (mp[x] = = 1 ):
cnt + = 1
return cnt
if __name__ = = "__main__" :
arr = [
[ 'a' , 'b' , 'c' , 'd' ],
[ 'a' , 'e' , 'f' , 'r' ],
[ 'a' , 'b' , 'c' , 'd' ],
[ 'z' , 'c' , 'e' , 'f' ],
]
print (uniqueRows(arr))
|
C#
using System;
using System.Collections;
using System.Collections.Generic;
class GFG{
static int uniqueRows( char [,]arr)
{
Dictionary< string ,
int > mp = new Dictionary< string ,
int >();
string t;
for ( int i = 0; i < arr.GetLength(0); i++)
{
t = "" ;
for ( int j = 0; j < arr.GetLength(1); j++)
{
t += arr[i, j];
}
if (mp.ContainsKey(t))
{
mp[t] = mp[t] + 1;
}
else
{
mp.Add(t, 1);
}
}
int cnt = 0;
foreach ( var x in mp.Keys)
{
if (mp[x] == 1)
{
cnt += 1;
}
}
return cnt;
}
public static void Main()
{
char [,]arr = { { 'a' , 'b' , 'c' , 'd' },
{ 'a' , 'e' , 'f' , 'r' },
{ 'a' , 'b' , 'c' , 'd' },
{ 'z' , 'c' , 'e' , 'f' }, };
Console.Write(uniqueRows(arr));
}
}
|
Javascript
<script>
function uniqueRows(arr) {
let mp = new Map();
let t;
for (let x of arr) {
t = "" ;
for (let y of x) {
t += y;
}
if (!mp.has(t))
mp.set(t, 1);
else
mp.set(t, mp.get(t) + 1);
}
let cnt = 0;
for (let [key, val] of mp) {
if (val == 1) {
cnt += 1;
}
}
return cnt;
}
let arr = [
[ 'a' , 'b' , 'c' , 'd' ],
[ 'a' , 'e' , 'f' , 'r' ],
[ 'a' , 'b' , 'c' , 'd' ],
[ 'z' , 'c' , 'e' , 'f' ],
];
document.write(uniqueRows(arr));
</script>
|
Time Complexity: O(N*M), Where N is the number of rows and M is the number of columns in the matrix
Auxiliary Space: O(N*M), Where N is the number of rows and M is the number of columns in the matrix
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...