Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Move from brute-force thinking to an efficient approach using array strategy.
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:
nums[i].nums[i].Return the number of ways to select a group of students so that everyone remains happy.
Example 1:
Input: nums = [1,1] Output: 2 Explanation: The two possible ways are: The class teacher selects no student. The class teacher selects both students to form the group. If the class teacher selects just one student to form a group then the both students will not be happy. Therefore, there are only two possible ways.
Example 2:
Input: nums = [6,0,3,3,6,7,2,7] Output: 3 Explanation: The three possible ways are: The class teacher selects the student with index = 1 to form the group. The class teacher selects the students with index = 1, 2, 3, 6 to form the group. The class teacher selects all the students to form the group.
Constraints:
1 <= nums.length <= 1050 <= nums[i] < nums.lengthProblem summary: 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.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array
[1,1]
[6,0,3,3,6,7,2,7]
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #2860: Happy Students
class Solution {
public int countWays(List<Integer> nums) {
Collections.sort(nums);
int n = nums.size();
int ans = 0;
for (int i = 0; i <= n; i++) {
if ((i == 0 || nums.get(i - 1) < i) && (i == n || nums.get(i) > i)) {
ans++;
}
}
return ans;
}
}
// Accepted solution for LeetCode #2860: Happy Students
func countWays(nums []int) (ans int) {
sort.Ints(nums)
n := len(nums)
for i := 0; i <= n; i++ {
if (i > 0 && nums[i-1] >= i) || (i < n && nums[i] <= i) {
continue
}
ans++
}
return
}
# Accepted solution for LeetCode #2860: Happy Students
class Solution:
def countWays(self, nums: List[int]) -> int:
nums.sort()
n = len(nums)
ans = 0
for i in range(n + 1):
if i and nums[i - 1] >= i:
continue
if i < n and nums[i] <= i:
continue
ans += 1
return ans
// Accepted solution for LeetCode #2860: Happy Students
/**
* [2860] Happy Students
*/
pub struct Solution {}
// submission codes start here
impl Solution {
pub fn count_ways(nums: Vec<i32>) -> i32 {
let mut nums: Vec<usize> = nums.iter().map(|x| *x as usize).collect();
let n = nums.len();
nums.sort();
// 是否能不选中任何学生
let mut result = 0;
for i in 0..=n {
if i > 0 && nums[i - 1] >= i {
continue;
}
if i < n && nums[i] <= i {
continue;
}
result += 1;
}
result
}
}
// submission codes end
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_2860() {
assert_eq!(2, Solution::count_ways(vec![1, 1]));
assert_eq!(3, Solution::count_ways(vec![6, 0, 3, 3, 6, 7, 2, 7]));
assert_eq!(1, Solution::count_ways(vec![1, 0, 1, 1]));
}
}
// Accepted solution for LeetCode #2860: Happy Students
function countWays(nums: number[]): number {
nums.sort((a, b) => a - b);
let ans = 0;
const n = nums.length;
for (let i = 0; i <= n; ++i) {
if ((i && nums[i - 1] >= i) || (i < n && nums[i] <= i)) {
continue;
}
++ans;
}
return ans;
}
Use this to step through a reusable interview workflow for this problem.
Two nested loops check every pair or subarray. The outer loop fixes a starting point, the inner loop extends or searches. For n elements this gives up to n²/2 operations. No extra space, but the quadratic time is prohibitive for large inputs.
Most array problems have an O(n²) brute force (nested loops) and an O(n) optimal (single pass with clever state tracking). The key is identifying what information to maintain as you scan: a running max, a prefix sum, a hash map of seen values, or two pointers.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.