algoadvance

Leetcode 1450. Number of Students Doing Homework at a Given Time

Problem Statement

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.

Clarifying Questions

  1. Are the arrays startTime and endTime of the same length?
    • Yes, each startTime[i] corresponds to an endTime[i] of the same student.
  2. Is queryTime guaranteed to be within the range of typical start and end times?
    • Yes, you can assume queryTime values are reasonable as per the usual constraints defined in such problems.
  3. What are the constraints on the length of the arrays, and the values within them?
    • Given the problem constraints on LeetCode, typically:
      • 1 <= startTime.length == endTime.length <= 1000
      • 1 <= startTime[i] <= endTime[i] <= 1000
      • 1 <= queryTime <= 1000

Code

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
    }
}

Strategy

  1. Initialization of Counter:
    • Initialize a variable count to zero. This will keep track of the number of students doing homework at queryTime.
  2. Iterate Through startTime and endTime:
    • Iterate through the arrays. For each student (each index i), check if queryTime is within the interval [startTime[i], endTime[i]].
  3. Condition Check:
    • If startTime[i] <= queryTime and queryTime <= endTime[i], increment the count.
  4. Return the Result:
    • After iterating through all the students, return the count as the result.

Time Complexity

This straightforward approach ensures efficient calculation with minimal overhead, making it suitable given the problem constraints.

Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI