Check if an array contains only one distinct element - GeeksforGeeks

17 Aug, 2021
Given an array arr[] of size N, the task is to check if the array contains only one distinct element or not. If it contains only one distinct element then print “Yes”, otherwise print “No”.
Examples:
Input: arr[] = {3, 3, 4, 3, 3} Output: No  Explanation: There are 2 distinct elements present in the array {3, 4}. Therefore, the output is No.
Input: arr[] = {9, 9, 9, 9, 9, 9, 9} Output: Yes Explanation: The only distinct element in the array is 9. Therefore, the output is Yes.
Naive Approach: The idea is to sort the given array and then for each valid index check if the current element and the next element are the same or not. If they are not the same it means the array contains more than one distinct element, therefore print “No”, otherwise print “Yes”.
Time Complexity: O(N*logN) Auxiliary Space: O(1)
Better Approach: This problem can be solved by using a set data structure. Since in set, no repetitions are allowed. Below are the steps:
Insert elements of the array into the set.If there is only one distinct element then the size of the set after step 1 will be 1, so print “Yes”.Otherwise, print “No”.
Insert elements of the array into the set.
If there is only one distinct element then the size of the set after step 1 will be 1, so print “Yes”.
Otherwise, print “No”.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find if the array// contains only one distinct elementvoid uniqueElement(int arr[],int n){         // Create a set    unordered_set<int> set;         // Traversing the array    for(int i = 0; i < n; i++)    {        set.insert(arr[i]);    }         // Compare and print the result    if(set.size() == 1)    {        cout << "YES" << endl;    }    else    {        cout << "NO" << endl;    }} // Driver codeint main(){    int arr[] = { 9, 9, 9, 9, 9, 9, 9 };         int n = sizeof(arr) / sizeof(arr[0]);         // Function call    uniqueElement(arr,n);    return 0;} // This code is contributed by rutvik_56
// Java program for the above approachimport java.util.*; public class Main {     // Function to find if the array    // contains only one distinct element    public static void    uniqueElement(int arr[])    {        // Create a set        Set<Integer> set = new HashSet<>();         // Traversing the array        for (int i = 0; i < arr.length; i++) {            set.add(arr[i]);        }         // Compare and print the result        if (set.size() == 1)            System.out.println("Yes");         else            System.out.println("No");    }     // Driver Code    public static void main(String args[])    {        int arr[] = { 9, 9, 9, 9, 9, 9, 9 };         // Function call        uniqueElement(arr);    }}
# Python3 program for the above approach # Function to find if the array# contains only one distinct elementdef uniqueElement(arr, n):         # Create a set    s = set(arr)         # Compare and print the result    if(len(s) == 1):        print('YES')    else:        print('NO') # Driver codeif __name__=='__main__':         arr = [ 9, 9, 9, 9, 9, 9, 9 ]    n = len(arr)         # Function call    uniqueElement(arr, n)     # This code is contributed by rutvik_56
// C# program for the above approachusing System;using System.Collections.Generic; class GFG{ // Function to find if the array// contains only one distinct elementpublic static void uniqueElement(int []arr){         // Create a set    HashSet<int> set = new HashSet<int>();     // Traversing the array    for(int i = 0; i < arr.Length; i++)    {        set.Add(arr[i]);    }     // Compare and print the result    if (set.Count == 1)        Console.WriteLine("Yes");    else        Console.WriteLine("No");} // Driver Codepublic static void Main(String []args){    int []arr = { 9, 9, 9, 9, 9, 9, 9 };     // Function call    uniqueElement(arr);}} // This code is contributed by Amit Katiyar
<script> // Javascript program for the above approach // Function to find if the array// contains only one distinct elementfunction uniqueElement(arr,n){         // Create a set    var set = new Set();         // Traversing the array    for(var i = 0; i < n; i++)    {        set.add(arr[i]);    }         // Compare and print the result    if(set.size == 1)    {        document.write( "YES");    }    else    {        document.write( "NO");    }} // Driver codevar arr = [9, 9, 9, 9, 9, 9, 9]; var n = arr.length; // Function calluniqueElement(arr,n); // This code is contributed by itsok.</script>
Yes
Time Complexity: O(N) Auxiliary Space: O(N)
Efficient Approach: This problem can also be solved without using any extra space. Below are the steps:
Assume the first element of the array to be the only unique element in the array and store its value in a variable say X.Then traverse the array and check if the current element is equal to X or not.If found to be true, then keep checking for all array elements. If no element is found to be different from X, print “Yes”.Otherwise, if any of the array elements is not equal to X, it means that the array contains more than one unique element. Hence, print “No”.
Assume the first element of the array to be the only unique element in the array and store its value in a variable say X.
Then traverse the array and check if the current element is equal to X or not.
If found to be true, then keep checking for all array elements. If no element is found to be different from X, print “Yes”.
Otherwise, if any of the array elements is not equal to X, it means that the array contains more than one unique element. Hence, print “No”.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for// the above approach#include<bits/stdc++.h>using namespace std;  // Function to find if the array// contains only one distinct elementvoid uniqueElement(int arr[], int n){  // Assume first element to  // be the unique element  int x = arr[0];   int flag = 1;   // Traversing the array  for (int i = 0; i < n; i++)  {    // If current element is not    // equal to X then break the    // loop and print No    if (arr[i] != x)    {      flag = 0;      break;    }  }   // Compare and print the result  if (flag == 1)    cout << "Yes";  else    cout << "No";}     // Driver Codeint main(){  int arr[] = {9, 9, 9,               9, 9, 9, 9};  int n = sizeof(arr) /          sizeof(arr[0]);   // Function call  uniqueElement(arr, n);} // This code is contributed by Chitranayal
// Java program for the above approach import java.util.*; public class Main {     // Function to find if the array    // contains only one distinct element    public static void    uniqueElement(int arr[])    {        // Assume first element to        // be the unique element        int x = arr[0];         int flag = 1;         // Traversing the array        for (int i = 0; i < arr.length; i++) {             // If current element is not            // equal to X then break the            // loop and print No            if (arr[i] != x) {                flag = 0;                break;            }        }         // Compare and print the result        if (flag == 1)            System.out.println("Yes");         else            System.out.println("No");    }     // Driver Code    public static void main(String args[])    {        int arr[] = { 9, 9, 9, 9, 9, 9, 9 };         // Function call        uniqueElement(arr);    }}
# Python3 program for the above approach # Function to find if the array# contains only one distinct elementdef uniqueElement(arr):     # Assume first element to    # be the unique element    x = arr[0]     flag = 1     # Traversing the array    for i in range(len(arr)):         # If current element is not        # equal to X then break the        # loop and print No        if(arr[i] != x):            flag = 0            break     # Compare and print the result    if(flag == 1):        print("Yes")    else:        print("No") # Driver Code # Given array arr[]arr = [ 9, 9, 9, 9, 9, 9, 9 ] # Function calluniqueElement(arr) # This code is contributed by Shivam Singh
// C# program for the above approachusing System; class GFG{ // Function to find if the array// contains only one distinct elementpublic static void uniqueElement(int []arr){         // Assume first element to    // be the unique element    int x = arr[0];     int flag = 1;     // Traversing the array    for(int i = 0; i < arr.Length; i++)    {                 // If current element is not        // equal to X then break the        // loop and print No        if (arr[i] != x)        {            flag = 0;            break;        }    }     // Compare and print the result    if (flag == 1)        Console.WriteLine("Yes");    else        Console.WriteLine("No");} // Driver codestatic public void Main (){    int []arr = { 9, 9, 9, 9, 9, 9, 9 };     // Function call    uniqueElement(arr);}} // This code is contributed by AnkitRai01
<script>    // javascript program for the above approach     // Function to find if the array// contains only one distinct element function uniqueElement(arr){          // Assume first element to    // be the unique element    var x = arr[0];      var flag = 1;      // Traversing the array    for(var i = 0; i < arr.length; i++)    {                  // If current element is not        // equal to X then break the        // loop and print No        if (arr[i] != x)        {            flag = 0;            break;        }    }      // Compare and print the result    if (flag == 1)        document.write("Yes");    else        document.write("No");}  // Driver code     var arr = [ 9, 9, 9, 9, 9, 9, 9 ];      // Function call    uniqueElement(arr);    </script>
Yes
Time Complexity: O(N) Auxiliary Space: O(1)
SHIVAMSINGH67
ankthon
amit143katiyar
rutvik_56
ukasp
bunnyram19
itsok
anikakapoor
cpp-set
Arrays
Hash
School Programming
Searching
Arrays
Searching
Hash
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Next Greater Element
Window Sliding Technique
Count pairs with given sum
Program to find sum of elements in a given array
Reversal algorithm for array rotation
Internal Working of HashMap in Java
Hashing | Set 1 (Introduction)
Count pairs with given sum
Hashing | Set 3 (Open Addressing)
Hashing | Set 2 (Separate Chaining)