Happy Students — LeetCode 2860 Python Solution

MediumArrayEnumerationSorting
Problem
#2860
Pattern
Sorting
Reading time
2 min

The 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.

Example

Input
nums = [1,1]
Output
2
Explanation
The two possible ways are:

Python solution

Python
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

Complexity

MeasureComplexity
TimeO(n \times \log n)
SpaceO(\log n) auxiliary

Pattern: Sorting

Spend O(n log n) once to buy an ordering that makes the rest of the problem trivial. LeetCode 2860. Happy Students is filed here because LeetCode tags it Sorting, which is the vocabulary this hub collects.

The sorting guide has the Python template for the pattern and the 401 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2860. Happy Students?
LeetCode 2860. Happy Students is rated Medium on LeetCode.
What is the time complexity of LeetCode 2860. Happy Students?
The Python solution on this page runs in O(n \times \log n).
What is the space complexity of LeetCode 2860. Happy Students?
The Python solution on this page uses O(\log n) auxiliary space.
What topics does LeetCode 2860. Happy Students cover?
LeetCode 2860. Happy Students is tagged Array, Enumeration and Sorting on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview