Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on Hash
  • Practice Hash
  • MCQs on Hash
  • Hashing Tutorial
  • Hash Function
  • Index Mapping
  • Collision Resolution
  • Open Addressing
  • Separate Chaining
  • Quadratic probing
  • Double Hashing
  • Load Factor and Rehashing
  • Advantage & Disadvantage
Open In App
Next Article:
Check for Array Contains Duplicate III
Next article icon

Check if an array contains only one distinct element

Last Updated : 17 Aug, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

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++
// 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 
Java
// 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);     } } 
Python3
# 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 
C#
// 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   
JavaScript
<script>  // Javascript program for the above approach  // Function to find if the array  // contains only one distinct element  function 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 code var arr = [9, 9, 9, 9, 9, 9, 9];  var n = arr.length;  // Function call uniqueElement(arr,n);  // This code is contributed by itsok. </script>  

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++
// 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 
Java
// 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
# 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 
C#
// 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 
JavaScript
<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> 

Output: 
Yes

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


Next Article
Check for Array Contains Duplicate III
author
jyoti369
Improve
Article Tags :
  • Searching
  • Hash
  • School Programming
  • DSA
  • Arrays
  • cpp-set
Practice Tags :
  • Arrays
  • Hash
  • Searching

Similar Reads

  • Count distinct elements in an array in Python
    Given an unsorted array, count all distinct elements in it. Examples: Input : arr[] = {10, 20, 20, 10, 30, 10} Output : 3 Input : arr[] = {10, 20, 20, 10, 20} Output : 2 We have existing solution for this article. We can solve this problem in Python3 using Counter method. Approach#1: Using Set() Thi
    2 min read
  • Count Distinct ( Unique ) elements in an array
    Given an array arr[] of length N, The task is to count all distinct elements in arr[]. Examples:  Input: arr[] = {10, 20, 20, 10, 30, 10}Output: 3Explanation: There are three distinct elements 10, 20, and 30. Input: arr[] = {10, 20, 20, 10, 20}Output: 2 Naïve Approach: Create a count variable and ru
    15 min read
  • Check if array elements are consecutive
    Given an unsorted array of numbers, the task is to check if the array consists of consecutive numbers. Examples: Input: arr[] = [5, 2, 3, 1, 4]Output: YesExplanation: Array has consecutive numbers from 1 to 5. Input: arr[] = [83, 78, 80, 81, 79, 82]Output: YesExplanation: Array has consecutive numbe
    15+ min read
  • Check if array contains duplicates
    Given an integer array arr[], check if the array contains any duplicate value. Examples: Input: arr[] = {4, 5, 6, 4}Output: trueExplanation: 4 is the duplicate value. Input: arr[] = {1, 2, 3, 4}Output: falseExplanation: All values are distinct. Table of Content [Naive Approach] By using two nested l
    12 min read
  • Check for Array Contains Duplicate III
    Given an integer array arr[] and two integers indexDifference and valueDifference, find a pair of indices (i, j) such that: i != jabs(i - j) <= indexDifferenceabs(arr[i] - arr[j]) <= valueDifferenceReturn true if such a pair exists, false otherwise. Example: Input: arr = [1,2,3,1], indexDiffer
    6 min read
  • Check if an Array is made up of Subarrays of continuous repetitions of every distinct element
    Given an array arr[], consisting of N integers, the task is to check whether the entire array is only made up of subarrays such that each subarray consists of consecutive repetitions of a single element and every distinct element in the array is part of such subarray. Examples: Input: N = 10, arr[]
    11 min read
  • How to check if an Array contains a value or not?
    There are many ways for checking whether the array contains any specific value or not, one of them is: Examples: Input: arr[] = {10, 30, 15, 17, 39, 13}, key = 17Output: True Input: arr[] = {3, 2, 1, 7, 10, 13}, key = 20Output: False Approach: Using in-built functions: In C language there is no in-b
    3 min read
  • Count pairs formed by distinct element sub-arrays
    Given an array, count number of pairs that can be formed from all possible contiguous sub-arrays containing distinct numbers. The array contains positive numbers between 0 to n-1 where n is the size of the array. Examples: Input: [1, 4, 2, 4, 3, 2] Output: 8 The subarrays with distinct elements are
    7 min read
  • Check if all subarrays contains at least one unique element
    Given an array arr[] consisting of N integers, the task is to check if all subarrays of the array have at least one unique element in it or not. If found to be true, then print "Yes". Otherwise, print "No". Examples: Input: arr[] = {1, 2, 1}Output: YesExplanation:For Subarrays of size 1: {1}, {2}, {
    11 min read
  • Find the only different element in an array
    Given an array of integers where all elements are same except one element, find the only different element in the array. It may be assumed that the size of the array is at least two.Examples: Input : arr[] = {10, 10, 10, 20, 10, 10} Output : 3 arr[3] is the only different element.Input : arr[] = {30
    10 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences