We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Number of Students Doing Homework at a Given Time

Number: 1560

Difficulty: Easy

Paid? No

Companies: N/A


Problem Description

Given two arrays, startTime and endTime, which represent when students start and finish their homework respectively, and an integer queryTime, determine how many students are doing homework at queryTime. A student is considered to be doing homework at queryTime if queryTime lies in the interval [startTime[i], endTime[i]].


Key Insights

  • The problem requires iterating through each student's start and end times.
  • For each student, check if queryTime is within their homework time interval.
  • A simple count is maintained as we check each student.
  • Given the constraints, a linear scan is both efficient and sufficient.

Space and Time Complexity

Time Complexity: O(n), where n is the number of students. Space Complexity: O(1), as we only use a counter and no additional data structures.


Solution

Iterate through the arrays startTime and endTime simultaneously. For each student, check if the queryTime lies between the start and end times (inclusive). If it does, increment a counter. Finally, return the counter. This approach uses a basic loop with a conditional check, making it straightforward and efficient for the given constraints.


Code Solutions

def busyStudent(startTime, endTime, queryTime):
    # Initialize a count of students doing homework
    count = 0
    # Iterate over each student's time interval
    for s, e in zip(startTime, endTime):
        # Check if queryTime lies within the interval [s, e]
        if s <= queryTime <= e:
            count += 1
    return count

# Example usage
print(busyStudent([1, 2, 3], [3, 2, 7], 4))  # Expected output: 1
← Back to All Questions