This post is part of the Algorithms Problem Solving series.
This is the number of students problem. The description looks like this:
Given two integer
given an integer
ith student started doing their homework at
startTime[i] and finished it at
Return the number of students doing their homework
queryTime. More formally, return the number
of students where
queryTime lays in the
[startTime[i], endTime[i]] inclusive.
Input: startTime = [1,2,3], endTime = [3,2,7], queryTime = 4 Output: 1 Input: startTime = , endTime = , queryTime = 4 Output: 1 Input: startTime = , endTime = , queryTime = 5 Output: 0 Input: startTime = [1,1,1,1], endTime = [1,3,2,4], queryTime = 7 Output: 0 Input: startTime = [9,8,7,6,5,4,3,2,1], endTime = [10,10,10,10,10,10,10,10,10], queryTime = 5 Output: 5
The idea is just to iterate through the lists and compare them with
query_time to see if it is in the interval between
start and end time. If it is, just increment the
number_of_students counter. After the for loop finishes,
return this value.
def busy_student(start_time, end_time, query_time): number_of_students = 0 for index in range(len(start_time)): start, end = start_time[index], end_time[index] if query_time >= start and query_time <= end: number_of_students += 1 return number_of_students
But we could also use the
zip function to iterate through
the list simultaneously:
def busy_student(start_time, end_time, query_time): number_of_students = 0 for start, end in zip(start_time, end_time): if query_time >= start and query_time <= end: number_of_students += 1 return number_of_students
The runtime complexity is
the number of integers in the