Happy Students - Problem

You are given a 0-indexed integer array nums of length n where n is the total number of students in the class. The class teacher tries to select a group of students so that all the students remain happy.

The ith student will become happy if one of these two conditions is met:

  • The student is selected and the total number of selected students is strictly greater than nums[i].
  • The student is not selected and the total number of selected students is strictly less than nums[i].

Return the number of ways to select a group of students so that everyone remains happy.

Input & Output

Example 1 — Simple Case
$ Input: nums = [1,1]
Output: 1
💡 Note: Only one way works: select no students. Both students are happy because 0 < 1, so they're satisfied being unselected.
Example 2 — Multiple Options
$ Input: nums = [6,0,3,3,6,7,2,3]
Output: 3
💡 Note: Three valid selection sizes work: selecting 0 students, 4 students, or 7 students can make everyone happy.
Example 3 — No Solution
$ Input: nums = [1,2,3]
Output: 0
💡 Note: No selection size can satisfy all students simultaneously due to conflicting requirements.

Constraints

  • 1 ≤ nums.length ≤ 50
  • 0 ≤ nums[i] < nums.length

Visualization

Tap to expand
Happy Students Problem INPUT nums array (n=2 students) 1 index 0 1 index 1 Student 0 needs >1 Student 1 needs >1 Happy Conditions: If selected: count > nums[i] If not selected: count < nums[i] Goal: Find valid group sizes ALGORITHM STEPS 1 Sort Array [1,1] --> [1,1] (same) 2 Check k=0 (none) 0 < nums[0]=1? Yes! Valid: count=1 3 Check k=1 1 > nums[0]=1? No Invalid 4 Check k=2 (all) 2 > nums[1]=1? Yes No next elem to check But k=2 needs all happy Enumeration Results k=0: 0<1 (OK) valid k=1: 1>1? No invalid k=2: 2>1 (OK) but tied FINAL RESULT Valid Selections Found k = 0 (Select None) Both students not selected 0 < 1, so both happy! k = 1 (Invalid) 1 is not > 1 k = 2 (Invalid) Both need count > 1 Output 1 Key Insight: After sorting, enumerate all possible group sizes k from 0 to n. For each k, check if selecting the k smallest students makes everyone happy: selected students need k > nums[i], and non-selected students need k < nums[i]. Early pruning skips invalid k values efficiently. TutorialsPoint - Happy Students | Optimized Enumeration with Early Pruning
Asked in
Google 12 Meta 8 Amazon 6
8.9K Views
Medium Frequency
~25 min Avg. Time
234 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen