Number of Students Doing Homework at a Given Time Problem
#1450
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 1450.
Given two integer arrays startTime and endTime and given an integer queryTime.
The ith student started doing their homework at the time startTime[i] and finished it at time endTime[i].
Return the number of students doing their homework at time queryTime. More formally, return the number of students where queryTime lays in the interval [startTime[i], endTime[i]] inclusive.
Example 1:
Input: startTime = [1,2,3], endTime = [3,2,7], queryTime = 4
Output: 1
Explanation: We have 3 students where:
The first student started doing homework at time 1 and finished at time 3 and wasn't doing anything at time 4.
The second student started doing homework at time 2 and finished at time 2 and also wasn't doing anything at time 4.
The third student started doing homework at time 3 and finished at time 7 and was the only student doing homework at time 4.
Example 2:
Input: startTime = [4], endTime = [4], queryTime = 4
Output: 1
Explanation: The only student was doing their homework at the queryTime.
Constraints:
startTime.length == endTime.length1 <= startTime.length <= 1001 <= startTime[i] <= endTime[i] <= 10001 <= queryTime <= 1000
Solution
Approach: Check Each Student
Student i is busy at queryTime exactly when startTime[i] <= queryTime <= endTime[i]. Both ends are inclusive, so a student who starts or finishes at queryTime counts (as in Example 2).
Go through the students and count how many satisfy that condition.
Complexity: O(n) time and O(1) extra space.
class Solution:
def busyStudent(self, startTime: List[int], endTime: List[int], queryTime: int) -> int:
return sum(1 for s, e in zip(startTime, endTime) if s <= queryTime <= e)