All elements in an array are Same or not? - GeeksforGeeks

29 Jan, 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. 
C++
Java
Python3
C#
Javascript
//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 codeint 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 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 codepublic 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");    }}
# Python 3 program to check if all# array are same or notdef 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 codeif __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# 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 codepublic 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
<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>
Not all Elements are Same
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.
C++
Java
Python3
C#
Javascript
// 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 codeint 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 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 codepublic 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 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 codeif __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# 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 codepublic 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
<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>
Not all Elements are Same
Time Complexity: O(n) Auxiliary Space: O(1) 
mohit kumar 29
Shashank_Sharma
amit143katiyar
29AjayKumar
GauravRajput1
Rajput-Ji
patel2127
unknown2108
surinderdawra388
java-hashset
Arrays
Hash
Arrays
Hash
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stack Data Structure (Introduction and Program)
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Multidimensional Arrays in Java
Introduction to Arrays
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Hashing | Set 1 (Introduction)
Hashing | Set 3 (Open Addressing)
Count pairs with given sum
Hashing | Set 2 (Separate Chaining)