Number of Students Doing Homework at a Given Time - Problem

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 lies in the interval [startTime[i], endTime[i]] inclusive.

Input & Output

Example 1 — Basic Case
$ Input: startTime = [1,2,3], endTime = [3,4,7], queryTime = 4
Output: 2
💡 Note: At time 4, students 1 and 2 are doing homework. Student 1: 2 ≤ 4 ≤ 4 (true), Student 2: 3 ≤ 4 ≤ 7 (true). Student 0 finished at time 3, so 1 ≤ 4 ≤ 3 is false.
Example 2 — Multiple Students
$ Input: startTime = [4], endTime = [4], queryTime = 4
Output: 1
💡 Note: Student starts and ends at time 4, so at queryTime 4, they are still doing homework (inclusive interval).
Example 3 — No Active Students
$ Input: startTime = [4], endTime = [4], queryTime = 5
Output: 0
💡 Note: Student finished at time 4, so at time 5 no one is doing homework.

Constraints

  • startTime.length == endTime.length
  • 1 ≤ startTime.length ≤ 100
  • 1 ≤ startTime[i] ≤ endTime[i] ≤ 1000
  • 1 ≤ queryTime ≤ 1000

Visualization

Tap to expand
Number of Students Doing Homework INPUT Timeline (0 to 8): 0 1 2 3 4 5 6 7 S1 S2 S3 queryTime=4 Input Arrays: startTime: 1 2 3 endTime: 3 4 7 queryTime = 4 ALGORITHM STEPS 1 Initialize count = 0 2 Loop Students For each student i = 0,1,2 3 Check Condition start[i] <= query <= end[i] i=0: 1<=4<=3? NO i=1: 2<=4<=4? YES i=2: 3<=4<=7? YES (Wait, 3<=4<=7 is true!) 4 Count Match count++ for each match FINAL RESULT At queryTime = 4: Student 1: [1,3] DONE Student 2: [2,4] WORKING Student 3: [3,7] WORKING Output: 2 2 students doing homework at time 4 Key Insight: Single pass O(n) solution - iterate through all students once and check if queryTime falls within their [startTime, endTime] interval. No sorting or complex data structures needed. TutorialsPoint - Number of Students Doing Homework at a Given Time | Single Pass with Early Insights
Asked in
Amazon 15 Google 12 Apple 8 Microsoft 6
32.4K Views
Medium Frequency
~8 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen