Skip to main content
Back to problems
#2860
Medium Algorithms

Happy students

Array Sorting Enumeration
50.9% acceptance
Feb 25, 2026
182
310
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.

Solution

Rust
Time O(n log n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn count_ways(mut nums: Vec<i32>) -> i32 {
    let n = nums.len() as i32;
    nums.sort();
    let mut ans = 0;
    // Try each group size m = 0..=n
    // Select m students: all selected must have nums[i] < m, all unselected must have nums[i] > m
    // After sorting: select the m students with smallest nums
    // Condition: nums[m-1] < m (last selected) and (m==n or nums[m] > m) (first unselected)
    for m in 0..=n {
      let left_ok = m == 0 || nums[(m - 1) as usize] < m;
      let right_ok = m == n || nums[m as usize] > m;
      if left_ok && right_ok { ans += 1; }
    }
    ans
  }
}