Check if an array contains only one distinct element

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:

  1. Insert elements of the array into the set.
  2. If there is only one distinct element then the size of the set after step 1 will be 1, so print “Yes”.
  3. Otherwise, print “No”.

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to find if the array
// contains only one distinct element
void 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 code
int 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

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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[])
    {
        // 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);
    }
}

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program for the above approach
 
# Function to find if the array
# contains only one distinct element
def uniqueElement(arr, n):
     
    # Create a set
    s = set(arr)
     
    # Compare and print the result
    if(len(s) == 1):
        print('YES')
    else:
        print('NO')
 
# Driver code
if __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

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program for the above approach
using System;
using System.Collections.Generic;
 
class GFG{
 
// Function to find if the array
// contains only one distinct element
public 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 Code
public 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

chevron_right


Output: 

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:

  1. 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.
  2. Then traverse the array and check if the current element is equal to X or not.
  3. If found to be true, then keep checking for all array elements. If no element is found to be different from X, print “Yes”.
  4. 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++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program for
// the above approach
#include<bits/stdc++.h>
using namespace std;
  
// Function to find if the array
// contains only one distinct element
void 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 Code
int 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

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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);
    }
}

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program for the above approach
 
# Function to find if the array
# contains only one distinct element
def 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 call
uniqueElement(arr)
 
# This code is contributed by Shivam Singh

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program for the above approach
using System;
 
class GFG{
 
// 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)
        Console.WriteLine("Yes");
    else
        Console.WriteLine("No");
}
 
// Driver code
static public void Main ()
{
    int []arr = { 9, 9, 9, 9, 9, 9, 9 };
 
    // Function call
    uniqueElement(arr);
}
}
 
// This code is contributed by AnkitRai01

chevron_right


Output: 

Yes

Time Complexity: O(N) 
Auxiliary Space: O(1)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up

Recommended Posts:


Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.