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;
// Function to check if the given row is unique or not
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;
}
// Function to find the number of unique rows in the given matrix
int countUniqueRows(vector<vector<char>> arr)
{
int count = 0;
for(int i=0; i<arr.size(); i++)
{
if(isUniqueRow(arr, i))
count++;
}
return count;
}
// Driver code
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):
"""
Function to check if the given row is unique or not.
"""
for i in range(row):
if arr[i] == arr[row]:
return False
return True
def countUniqueRows(arr):
"""
Function to find the number of unique rows in the given matrix.
"""
count = 0
for i in range(len(arr)):
if isUniqueRow(arr, i):
count += 1
return count
# Driver code
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 to check if the given row is unique or not
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 to find the number of unique rows in the given matrix
function countUniqueRows(arr) {
let count = 0;
for (let i = 0; i < arr.length; i++) {
if (isUniqueRow(arr, i)) {
count++;
}
}
return count;
}
// Driver code
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 {
// Function to check if the given row is unique or not
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;
}
// Function to find the number of unique rows in the
// given matrix
static int countUniqueRows(char[][] arr)
{
int count = 0;
for (int i = 0; i < arr.length; i++) {
if (isUniqueRow(arr, i)) {
count++;
}
}
return count;
}
// Driver code
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
{
// Function to check if the given row is unique or not
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;
}
// Function to find the number of unique rows in the given matrix
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;
}
// Driver code
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));
}
}
OutputNumber 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++
// C++ code to implement the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to find number of unique rows
int uniqueRows(vector<vector<char> > arr)
{
// Map to store the frequency of
// each row as string
unordered_map<string, int> mp;
string t;
for (auto x : arr) {
t = "";
for (auto y : x) {
t += y;
}
mp[t] += 1;
}
int cnt = 0;
// Counting unique rows
for (auto x : mp) {
if (x.second == 1) {
cnt += 1;
}
}
return cnt;
}
// Driver Code
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
// Java code to implement the above approach
import java.util.*;
class GFG{
// Function to find number of unique rows
static int uniqueRows(char[][] arr)
{
// Map to store the frequency of
// each row as String
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;
// Counting unique rows
for (Map.Entry<String,Integer> x : mp.entrySet()) {
if (x.getValue() == 1) {
cnt += 1;
}
}
return cnt;
}
// Driver Code
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));
}
}
// This code is contributed by Rajput-Ji
Python3
# Python 3 code to implement the above approach
from collections import defaultdict
# Function to find number of unique rows
def uniqueRows(arr):
# Map to store the frequency of
# each row as string
mp = defaultdict(int)
t = ""
for x in arr:
t = ""
for y in x:
t += y
mp[t] += 1
cnt = 0
# Counting unique rows
for x in mp:
if (mp[x] == 1):
cnt += 1
return cnt
# Driver Code
if __name__ == "__main__":
arr = [
['a', 'b', 'c', 'd'],
['a', 'e', 'f', 'r'],
['a', 'b', 'c', 'd'],
['z', 'c', 'e', 'f'],
]
print(uniqueRows(arr))
# This code is contributed by ukasp.
C#
// C# code to implement the above approach
using System;
using System.Collections;
using System.Collections.Generic;
class GFG{
// Function to find number of unique rows
static int uniqueRows(char [,]arr)
{
// Map to store the frequency of
// each row as string
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;
// Counting unique rows
foreach(var x in mp.Keys)
{
if (mp[x] == 1)
{
cnt += 1;
}
}
return cnt;
}
// Driver Code
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));
}
}
// This code is contributed by Samim Hossain Mondal.
JavaScript
<script>
// JavaScript code for the above approach
// Function to find number of unique rows
function uniqueRows(arr) {
// Map to store the frequency of
// each row as string
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;
// Counting unique rows
for (let [key, val] of mp) {
if (val == 1) {
cnt += 1;
}
}
return cnt;
}
// Driver Code
let arr = [
['a', 'b', 'c', 'd'],
['a', 'e', 'f', 'r'],
['a', 'b', 'c', 'd'],
['z', 'c', 'e', 'f'],
];
document.write(uniqueRows(arr));
// This code is contributed by Potta Lokesh
</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
Similar Reads
Print unique rows in a given Binary matrix Given a binary matrix, print all unique rows of the given matrix. Example: Input: {0, 1, 0, 0, 1} {1, 0, 1, 1, 0} {0, 1, 0, 0, 1} {1, 1, 1, 0, 0} Output: 0 1 0 0 1 1 0 1 1 0 1 1 1 0 0 Explanation: The rows are r1={0, 1, 0, 0, 1}, r2={1, 0, 1, 1, 0}, r3={0, 1, 0, 0, 1}, r4={1, 1, 1, 0, 0}, As r1 = r3
15+ min read
Count of palindromic plus paths in a given Matrix Given an N x M matrix of integers, the task is to count the number of palindromic pluses in the array. Palindromic plus is formed when a palindromic sub-row and palindromic sub-column cross each other at the middle element. Examples: Input: matrix = [[1, 2, 1], [2, 3, 2], [3, 2, 1]] Output: 1 Explan
6 min read
Count of submatrix with sum X in a given Matrix Given a matrix of size N x M and an integer X, the task is to find the number of sub-squares in the matrix with sum of elements equal to X.Examples: Input: N = 4, M = 5, X = 10, arr[][]={{2, 4, 3, 2, 10}, {3, 1, 1, 1, 5}, {1, 1, 2, 1, 4}, {2, 1, 1, 1, 3}} Output: 3 Explanation: {10}, {{2, 4}, {3, 1}
15+ min read
Count of palindromic rows in given Matrix Given a matrix arr[][] of size N * N, the task is to find the number of palindromic rows. Examples: Input: arr[][] = {{1, 3, 1}, {2, 2, 3}, {2, 1, 2}} Output: 2Explanation: First and third row forms a palindrome i.e 1 3 1 and 2 1 2. Therefore, count of palindromic rows is 2. Input: arr[][] = {{2, 2,
4 min read
Grid Unique Paths - Count Paths in matrix Given an matrix of size m x n, the task is to find the count of all unique possible paths from top left to the bottom right with the constraints that from each cell we can either move only to the right or down.Examples: Input: m = 2, n = 2Output: 2Explanation: There are two paths(0, 0) -> (0, 1)
15+ min read
Common elements in all rows of a given matrix Given an m x n matrix, find all common elements present in all rows in O(mn) time and one traversal of matrix.Example: Input:mat[4][5] = {{1, 2, 1, 4, 8}, {3, 7, 8, 5, 1}, {8, 7, 7, 3, 1}, {8, 1, 2, 7, 9}, };Output: 1 8 or 8 18 and 1 are present in all rows.A simple solution is to consider every ele
7 min read
Find the count of mountains in a given Matrix Given a 2D square matrix of size N X N, the task is to count the number of mountains in the matrix. An element in a matrix is said to be a mountain when all the surrounding elements (in all 8 directions) are smaller than the given element. Examples: Input: matrix = { { 4, 5, 6 }, { 2, 1, 3 }, { 7, 8
9 min read
Find unique elements in a matrix Given a matrix mat[][] having n rows and m columns. The task is to find unique elements in the matrix i.e., those elements which are not repeated in the matrix or those elements whose frequency is 1. Examples: Input: mat[][] = [[2, 1, 4, 3], [1, 2, 3, 2], [3, 6, 2, 3], [5, 2, 5, 3]]Output: 4 6Input:
5 min read
Count all sorted rows in a matrix Given a matrix of m*n size, the task is to count all the rows in a matrix that are sorted either in strictly increasing order or in strictly decreasing order?Examples : Input : m = 4, n = 5 mat[m][n] = 1 2 3 4 5 4 3 1 2 6 8 7 6 5 4 5 7 8 9 10Output: 3The idea is simple and involves two traversals of
10 min read
Count rows in a matrix that consist of same element Given a matrix mat[][], the task is to count the number of rows in the matrix that consists of the same elements. Examples: Input: mat[][] = {{1, 1, 1}, {1, 2, 3}, {5, 5, 5}} Output: 2 All the elements of the first row and all the elements of the third row are the same. Input: mat[][] = {{1, 2}, {4,
9 min read