Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • 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
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Program to find the number of persons wearing white hat
Next article icon

Program to find the number of persons wearing white hat

Last Updated : 19 Sep, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

There are N persons in a room, each of them wearing a hat which is either black or white. Every person counts the number of other persons wearing the white hat. Given the number of counts of each person, the task is to find the number of persons wearing white hats, or print -1 if the given counts don't correspond to a valid situation.

Examples: 

Input : arr[] = {2, 1, 1}.  Output : 2  First person sees two white hats. Second  and third persons see one white hat. The   first person must be wearing a black hat  and other two must be wearing a white hat.    Input : arr[] = {2, 2, 2}  Output : 3  All are wearing white hats.    Input : arr[] = {10, 10}  Output : -1  There are only two persons, count can't be 10.

There are only two kinds of persons. If each person counts correctly (valid situation), then the count value of each person wearing white hat is same. And also, the count value of each person wearing black hat is same. So there will be only one or two types of value in the array. 

Let the number of white hats be i, 0 <= i <= N-1. 
Now observe for each person wearing the white hat, the count value will be i - 1. So there will be i persons whose count will be i-1. 
Also the number of persons wearing the black hats will be, N - i and their given count value will be i. 
An interesting case is with zero white hats. If all values are 0, then everybody is wearing a black hat. Otherwise there can be at most one zero for the case when there is single person wearing a white hat. In case of one zero, all other entries must be 1.

Algorithm for solving this problem: 

  1. Count the frequency of each element of the array.
  2. Since there are one or two types, say x and y.
    1. If the number of x's equal to x + 1 and number of y's equal to n - y. The Number of hats equal to y or x + 1.
    2. Otherwise print -1. 

Explained example: 

Suppose, N = 5, the number of white hats can be range   from 0 to 4.  For white hats = 1, array will be {0, 1, 1, 1, 1}.  Number of 0's = 0 + 1 = 1.   Number of 1's = 5 - 1 = 4.    For white hats = 2, array will be {1, 1, 2, 2, 2}.  Number of 1's = 1 + 1 = 2.   Number of 2's = 5 - 3 = 2.    For white hats = 3, array will be {2, 2, 2, 3, 3}.  Number of 2's = 2 + 1 = 3.   Number of 3's = 5 - 3 = 2.    For white hats = 5, array will be {4, 4, 4, 4, 4}.  Number of 4's = 4 + 1 = 5.   Number of 5's = 5 - 5 = 0. 

Below is the implementation of this approach: 

CPP
// C++ program to count number of white hats #include<bits/stdc++.h> using namespace std;  // Given counts of White hats seen by n people, // return count of white hats. int numOfWhiteHats(int arr[], int n) {     // Counting frequencies of all values in given     // array     int freq[n+1];     memset(freq, 0, sizeof(freq));     for (int i=0; i<n; i++)     {         // Count of White hats cannot be more than         // n for n persons.         if (arr[i] >= n)             return -1;         freq[arr[i]]++;     }      // Counting number of different frequencies     int diffFreq = 0;     for (int i = n-1; i >= 0; i--)         if (freq[i])             diffFreq++;      // Cases where all the persons wearing white hat.     if (diffFreq == 1 && freq[n-1] == n)         return n;      // Case where no one wearing white hat.     if (diffFreq == 1 && freq[0] == n)         return 0;      // Else : number of distinct frequency must be 2.     if (diffFreq != 2)         return -1;      // Finding the last frequency with non zero value.     // Note that we traverse from right side.     int k;     for (k = n-1; k >= 1; k--)         if (freq[k])             break;      // Checking number of k's must be n - k.     // And number of (k-1)'s must be k.     if (freq[k-1] == k && freq[k] + k == n)         return freq[k-1];     else         return -1; }  // Driver code int main() {     int arr[] = {2, 2, 2, 3, 3};     int n = sizeof(arr)/sizeof(arr[0]);     cout << numOfWhiteHats(arr, n);     return 0; } 
Java
// Java program to count number of white hats import java.util.Arrays;  class GFG {          // Given counts of White hats seen by n      // people, return count of white hats.     static int numOfWhiteHats(int arr[], int n)     {                  // Counting frequencies of all values          // in given array         int freq[] = new int[n + 1];         Arrays.fill(freq, 0);                  for (int i = 0; i < n; i++) {                          // Count of White hats cannot be              // more than n for n persons.             if (arr[i] >= n)                 return -1;                              freq[arr[i]]++;         }          // Counting number of different          // frequencies         int diffFreq = 0;                  for (int i = n - 1; i >= 0; i--)             if (freq[i] > 0)                 diffFreq++;          // Cases where all the persons wearing          // white hat.         if (diffFreq == 1 && freq[n - 1] == n)             return n;          // Case where no one wearing white hat.         if (diffFreq == 1 && freq[0] == n)             return 0;          // Else : number of distinct frequency          // must be 2.         if (diffFreq != 2)             return -1;          // Finding the last frequency with non          // zero value.         // Note that we traverse from right side.         int k;                  for (k = n - 1; k >= 1; k--)             if (freq[k] > 0)                 break;          // Checking number of k's must be n - k.         // And number of (k-1)'s must be k.         if (freq[k - 1] == k && freq[k] + k == n)             return freq[k - 1];         else             return -1;     }          // Driver code     public static void main(String[] args)     {         int arr[] = { 2, 2, 2, 3, 3 };         int n = arr.length;         System.out.print(numOfWhiteHats(arr, n));     } }  // This code is contributed by Anant Agarwal. 
Python3
# python program to count # number of white hats  def numOfWhiteHats(arr, n):      # Counting frequencies of     # all values in given     # array     freq=[0 for i in range(n + 1 + 1)]     for i in range(n):              # Count of White hats         # cannot be more than         # n for n persons.         if (arr[i] >= n):             return -1         freq[arr[i]]+=1            # Counting number of     # different frequencies     diffFreq = 0     for i in range(n-1,-1,-1):         if (freq[i]):             diffFreq+=1       # Cases where all the     # persons wearing white hat.     if (diffFreq == 1 and freq[n-1] == n):         return n       # Case where no one     # wearing white hat.     if (diffFreq == 1 and freq[0] == n):         return 0       # Else : number of distinct     # frequency must be 2.     if (diffFreq != 2):         return -1       # Finding the last frequency     # with non zero value.     # Note that we traverse     # from right side.     for k in range(n - 1, 0, -1):         if (freq[k]):             break       # Checking number of k's     # must be n - k.     # And number of (k-1)'s     # must be k.     if (freq[k-1] == k and freq[k] + k == n):         return freq[k-1]     else:         return -1   # Driver code  arr= [2, 2, 2, 3, 3] n= len(arr) print(numOfWhiteHats(arr, n))  # This code is contributed # by Anant Agarwal. 
C#
// C# program to count number of white hats using System;  class GFG {          // Given counts of White hats seen by n      // people, return count of white hats.     static int numOfWhiteHats(int []arr, int n)     {         // Counting frequencies of all values          // in given array         int []freq = new int[n + 1];         //Arrays.fill(freq, 0);                  for (int i = 0; i < n; i++) {                          // Count of White hats cannot be              // more than n for n persons.             if (arr[i] >= n)                 return -1;                              freq[arr[i]]++;         }          // Counting number of different          // frequencies         int diffFreq = 0;                  for (int i = n - 1; i >= 0; i--)             if (freq[i] > 0)                 diffFreq++;          // Cases where all the persons wearing          // white hat.         if (diffFreq == 1 && freq[n - 1] == n)             return n;          // Case where no one wearing white hat.         if (diffFreq == 1 && freq[0] == n)             return 0;          // Else : number of distinct frequency          // must be 2.         if (diffFreq != 2)             return -1;          // Finding the last frequency with non          // zero value.         // Note that we traverse from right side.         int k;                  for (k = n - 1; k >= 1; k--)             if (freq[k] > 0)                 break;          // Checking number of k's must be n - k.         // And number of (k-1)'s must be k.         if (freq[k - 1] == k && freq[k] + k == n)             return freq[k - 1];         else             return -1;     }          // Driver code     public static void Main()     {         int []arr = {2, 2, 2, 3, 3};         int n = arr.Length;         Console.WriteLine(numOfWhiteHats(arr, n));     } }  // This code is contributed by vt_m. 
JavaScript
<script> // javascript program to count number of white hats      // Given counts of White hats seen by n     // people, return count of white hats.     function numOfWhiteHats(arr, n)     {          // Counting frequencies of all values         // in given array         var freq = Array(n + 1).fill(0);         for (i = 0; i < n; i++)         {              // Count of White hats cannot be             // more than n for n persons.             if (arr[i] >= n)                 return -1;             freq[arr[i]]++;         }          // Counting number of different         // frequencies         var diffFreq = 0;         for (i = n - 1; i >= 0; i--)             if (freq[i] > 0)                 diffFreq++;          // Cases where all the persons wearing         // white hat.         if (diffFreq == 1 && freq[n - 1] == n)             return n;          // Case where no one wearing white hat.         if (diffFreq == 1 && freq[0] == n)             return 0;          // Else : number of distinct frequency         // must be 2.         if (diffFreq != 2)             return -1;          // Finding the last frequency with non         // zero value.         // Note that we traverse from right side.         var k;          for (k = n - 1; k >= 1; k--)             if (freq[k] > 0)                 break;          // Checking number of k's must be n - k.         // And number of (k-1)'s must be k.         if (freq[k - 1] == k && freq[k] + k == n)             return freq[k - 1];         else             return -1;     }      // Driver code     var arr = [ 2, 2, 2, 3, 3 ];     var n = arr.length;     document.write(numOfWhiteHats(arr, n));  // This code is contributed by Rajput-Ji. </script> 

Output
3

Time Complexity: O(n)

Space Complexity: O(n) (we need to create a freq[] array of size n+1)

 


Next Article
Program to find the number of persons wearing white hat

K

kartik
Improve
Article Tags :
  • Arrays
  • DSA
Practice Tags :
  • Arrays

Similar Reads

    Number of different positions where a person can stand
    A person stands in the line of n people, but he doesn't know exactly which position he occupies. He can say that there are no less than 'f' people standing in front of him and no more than 'b' people standing behind him. The task is to find the number of different positions he can occupy. Examples:
    3 min read
    Lex Program to count number of words
    Lex is a computer program that generates lexical analyzers and was written by Mike Lesk and Eric Schmidt. Lex reads an input stream specifying the lexical analyzer and outputs source code implementing the lexer in the C programming language. Prerequisite: Flex (Fast lexical Analyzer Generator) Examp
    1 min read
    Find the number of spectators standing in the stadium at time t
    There are n spectators in the stadium, labeled from 1 to n. At time 1, the first spectator stands. At time 2, the second spectator stands. ... At time k, the k-th spectator stands. At time k + 1, the (k + 1)-th spectator stands and the first spectator sits. At time k + 2, the (k + 2)-th spectator st
    7 min read
    Program to Count numbers on fingers
    Count the given numbers on your fingers and find the correct finger on which the number ends. Examples: Input : 17 Output :1 Input :27 Output :3 Recommended PracticeFinger GameTry It! Approach: The first number starts from the thumb, second on the index finger, third on the middle finger, fourth on
    7 min read
    Program to count vowels, consonant, digits and special characters in string.
    Given a string and the task is to count vowels, consonant, digits and special character in string. Special character also contains the white space.Examples: Input : str = "geeks for geeks121" Output : Vowels: 5 Consonant: 8 Digit: 3 Special Character: 2 Input : str = " A1 B@ d adc" Output : Vowels:
    6 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