All elements in an array are Same or not?
Last Updated :
30 Aug, 2022
Given an array, check whether all elements in an array are the same or not.
Examples:
Input : "Geeks", "for", "Geeks"
Output : Not all Elements are Same
Input : 1, 1, 1, 1, 1
Output : All Elements are Same
Method 1 (Hashing): We create an empty HashSet, insert all elements into it, then we finally see if the size of the HashSet is one or not.
Implementation:
C++
//c++ program to check if all array are same or not
#include<bits/stdc++.h>
using namespace std;
bool areSame(int a[],int n)
{
unordered_map<int,int> m;//hash map to store the frequency of every
//element
for(int i=0;i<n;i++)
m[a[i]]++;
if(m.size()==1)
return true;
else
return false;
}
//Driver code
int main()
{
int arr[]={1,2,3,2};
int n=sizeof(arr)/sizeof(arr[0]);
if(areSame(arr,n))
cout<<"All Elements are Same";
else
cout<<"Not all Elements are Same";
}
Java
// Java program to check if all array elements are
// same or not.
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public class SameElements {
public static boolean areSame(Integer arr[])
{
// Put all array elements in a HashSet
Set<Integer> s = new HashSet<>(Arrays.asList(arr));
// If all elements are same, size of
// HashSet should be 1. As HashSet contains only distinct values.
return (s.size() == 1);
}
// Driver code
public static void main(String[] args)
{
Integer[] arr = { 1, 2, 3, 2 };
if (areSame(arr))
System.out.println("All Elements are Same");
else
System.out.println("Not all Elements are Same");
}
}
Python3
# Python 3 program to check if all
# array are same or not
def areSame(a, n):
m = {i:0 for i in range(len(a))}
# hash map to store the frequency
# of every element
for i in range(n):
m[a[i]] += 1
if(len(m) == 1):
return True
else:
return False
# Driver code
if __name__ == '__main__':
arr = [1, 2, 3, 2]
n = len(arr)
if(areSame(arr, n)):
print("All Elements are Same")
else:
print("Not all Elements are Same")
# This code is contributed by
# Shashank_Sharma
C#
// C# program to check if all array elements
// are same or not.
using System;
using System.Collections.Generic;
class GFG{
public static bool areSame(int []arr)
{
// Put all array elements in a HashSet
HashSet<int> s = new HashSet<int>();
for(int i = 0; i < arr.Length; i++)
s.Add(arr[i]);
// If all elements are same, size of
// HashSet should be 1. As HashSet
// contains only distinct values.
return (s.Count == 1);
}
// Driver code
public static void Main(String[] args)
{
int[] arr = { 1, 2, 3, 2 };
if (areSame(arr))
Console.WriteLine("All Elements are Same");
else
Console.WriteLine("Not all Elements are Same");
}
}
// This code is contributed by Amit Katiyar
JavaScript
<script>
// Javascript program to check if all array elements are
// same or not.
function areSame(arr)
{
// Put all array elements in a HashSet
let s = new Set(arr);
// If all elements are same, size of
// HashSet should be 1. As HashSet contains only distinct values.
return (s.size == 1);
}
// Driver code
let arr=[1, 2, 3, 2];
if (areSame(arr))
document.write("All Elements are Same");
else
document.write("Not all Elements are Same");
// This code is contributed by patel2127
</script>
OutputNot all Elements are Same
Complexity Analysis:
- Time Complexity: O(n)
- Auxiliary Space: O(n)
Method 2 (Compare with first): The idea is simple. We compare every other element with first. If all matches with first, we return true. Else we return false.
Implementation:
C++
// C++ Program to implement
// the above approach
#include <bits/stdc++.h>
using namespace std;
bool areSame(int arr[],
int n)
{
int first = arr[0];
for (int i = 1; i < n; i++)
if (arr[i] != first)
return 0;
return 1;
}
// Driver code
int main()
{
int arr[] = {1, 2, 3, 2};
int n = sizeof(arr) /
sizeof(arr[0]);
if (areSame(arr, n))
cout << "All Elements are Same";
else
cout << "Not all Elements are Same";
}
// This code is contributed by gauravrajput1
Java
// Java program to check if all array elements are
// same or not.
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public class SameElements {
public static boolean areSame(Integer arr[])
{
Integer first = arr[0];
for (int i=1; i<arr.length; i++)
if (arr[i] != first)
return false;
return true;
}
// Driver code
public static void main(String[] args)
{
Integer[] arr = { 1, 2, 3, 2 };
if (areSame(arr))
System.out.println("All Elements are Same");
else
System.out.println("Not all Elements are Same");
}
}
Python3
# Python3 program to check
# if all array elements are
# same or not.
def areSame(arr):
first = arr[0];
for i in range(1, len(arr)):
if (arr[i] != first):
return False;
return True;
# Driver code
if __name__ == '__main__':
arr = [1, 2, 3, 2];
if (areSame(arr)):
print("All Elements are Same");
else:
print("Not all Elements are Same");
# This code is contributed by Rajput-Ji
C#
// C# program to check if all
// array elements are same or not.
using System;
class SameElements{
static bool areSame(int []arr)
{
int first = arr[0];
for (int i = 1;
i < arr.Length; i++)
if (arr[i] != first)
return false;
return true;
}
// Driver code
public static void Main(String[] args)
{
int[] arr = {1, 2, 3, 2};
if (areSame(arr))
Console.WriteLine("All Elements are Same");
else
Console.WriteLine("Not all Elements are Same");
}
}
// This code is contributed by 29AjayKumar
JavaScript
<script>
// JavaScript program to check if all array elements are
// same or not.
function areSame(arr)
{
let first = arr[0];
for (let i=1; i<arr.length; i++)
if (arr[i] != first)
return false;
return true;
}
// Driver code
let arr=[1, 2, 3, 2 ];
if (areSame(arr))
document.write("All Elements are Same<br>");
else
document.write("Not all Elements are Same<br>");
// This code is contributed by unknown2108
</script>
OutputNot all Elements are Same
Complexity Analysis:
- Time Complexity: O(n)
- Auxiliary Space: O(1)
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
SQL Commands | DDL, DQL, DML, DCL and TCL Commands SQL commands are crucial for managing databases effectively. These commands are divided into categories such as Data Definition Language (DDL), Data Manipulation Language (DML), Data Control Language (DCL), Data Query Language (DQL), and Transaction Control Language (TCL). In this article, we will e
7 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Dijkstra's Algorithm to find Shortest Paths from a Source to all Given a weighted undirected graph represented as an edge list and a source vertex src, find the shortest path distances from the source vertex to all other vertices in the graph. The graph contains V vertices, numbered from 0 to V - 1.Note: The given graph does not contain any negative edge. Example
12 min read