Leetcode 1450. Number of Students Doing Homework at a Given Time
Given two integer arrays startTime
and endTime
and an integer queryTime
. startTime[i]
and endTime[i]
represent the start and end times of the i-th
student’s homework session, respectively. Return the number of students doing their homework at queryTime
. More formally, return the number of students where queryTime
lays in the interval [startTime[i], endTime[i]]
inclusive.
startTime
and endTime
of the same length?
startTime[i]
corresponds to an endTime[i]
of the same student.queryTime
guaranteed to be within the range of typical start and end times?
queryTime
values are reasonable as per the usual constraints defined in such problems.1 <= startTime.length == endTime.length <= 1000
1 <= startTime[i] <= endTime[i] <= 1000
1 <= queryTime <= 1000
public class HomeworkChecker {
public int busyStudent(int[] startTime, int[] endTime, int queryTime) {
int count = 0;
for (int i = 0; i < startTime.length; i++) {
if (startTime[i] <= queryTime && queryTime <= endTime[i]) {
count++;
}
}
return count;
}
public static void main(String[] args) {
HomeworkChecker checker = new HomeworkChecker();
int[] startTime = {1, 2, 3};
int[] endTime = {3, 2, 7};
int queryTime = 4;
System.out.println(checker.busyStudent(startTime, endTime, queryTime)); // Should print 1
}
}
count
to zero. This will keep track of the number of students doing homework at queryTime
.startTime
and endTime
:
i
), check if queryTime
is within the interval [startTime[i], endTime[i]]
.startTime[i] <= queryTime
and queryTime <= endTime[i]
, increment the count
.count
as the result.O(n)
n
is the length of the arrays startTime
and endTime
. The solution involves a single loop through these arrays.O(1)
This straightforward approach ensures efficient calculation with minimal overhead, making it suitable given the problem constraints.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?