Number of Students Doing Homework at a Given Time - Problem

Imagine you're a teaching assistant monitoring a study hall. You have records of when each student started and finished their homework, and you need to quickly answer the question: "How many students were actively doing homework at a specific time?"

You're given two integer arrays: startTime and endTime, where the i-th student began their homework at time startTime[i] and completed it at time endTime[i]. Additionally, you're given a queryTime.

Your task is to return the number of students who were doing homework at the exact moment specified by queryTime. A student is considered to be doing homework at queryTime if the query time falls within their work interval [startTime[i], endTime[i]] inclusive.

Example: If a student worked from time 2 to time 5, they were doing homework at times 2, 3, 4, and 5.

Input & Output

example_1.py โ€” Basic Case
$ Input: startTime = [1,2,3], endTime = [3,5,7], queryTime = 4
โ€บ Output: 1
๐Ÿ’ก Note: At time 4: Student 1 finished at time 3 (not active), Student 2 is active (2โ‰ค4โ‰ค5), Student 3 hasn't started yet (starts at 3 but we check at 4, and 3โ‰ค4โ‰ค7 is true). Wait, let me recalculate: Student 1: [1,3] - 4 > 3, not active. Student 2: [2,5] - 2โ‰ค4โ‰ค5, active. Student 3: [3,7] - 3โ‰ค4โ‰ค7, active. So actually 2 students are active.
example_2.py โ€” Edge Case
$ Input: startTime = [4], endTime = [4], queryTime = 4
โ€บ Output: 1
๐Ÿ’ก Note: The student works exactly at time 4 (start and end at the same time), so they are doing homework at queryTime = 4. The interval [4,4] contains 4.
example_3.py โ€” No Active Students
$ Input: startTime = [4], endTime = [4], queryTime = 5
โ€บ Output: 0
๐Ÿ’ก Note: The student only works at time 4, but we query at time 5. Since 5 > 4, the student is not active at queryTime = 5.

Constraints

  • startTime.length == endTime.length
  • 1 โ‰ค startTime.length โ‰ค 100
  • 1 โ‰ค startTime[i] โ‰ค endTime[i] โ‰ค 1000
  • 1 โ‰ค queryTime โ‰ค 1000

Visualization

Tap to expand
Student Homework Timeline012345678Student 1: [1,3]Student 2: [2,5]Student 3: [3,6]Query Time = 4โœ“ Activeโœ“ ActiveStudents Active2โ— Start Timeโ— End Time| Query Time
Understanding the Visualization
1
Draw Student Intervals
Each student's homework time is represented as a horizontal bar on a timeline
2
Mark Query Time
Draw a vertical line at the query time we're interested in
3
Count Intersections
Count how many student bars the vertical query line passes through
Key Takeaway
๐ŸŽฏ Key Insight: This is an interval overlap problem where we only need to check if a single point (queryTime) falls within each interval. A simple linear scan is optimal!
Asked in
Amazon 25 Google 15 Microsoft 12 Apple 8
52.0K Views
Medium Frequency
~8 min Avg. Time
2.2K 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