The Employee That Worked on the Longest Task

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution:
    def hardestWorker(self, n: int, logs: List[List[int]]) -> int:
        ans = 0
        prev = 0
        longest_duration = -1
        for log in logs:
            duration = log[1] - prev
            if longest_duration == -1 or duration >= longest_duration:
                if duration == longest_duration:
                    ans = min(log[0], ans)
                else:
                    ans = log[0]
            longest_duration = max(longest_duration, duration)
            prev = log[1]
        return ans

The function hardestWorker is trying to find the worker who has the longest continuous working duration. If there are multiple workers with the same longest duration, the function returns the worker with the smallest ID.

Here’s a detailed breakdown of the code:

  1. It initializes ans (the ID of the worker with the longest duration so far) to 0, prev (the ending time of the previous log) to 0, and longest_duration (the longest duration so far) to -1.

  2. The function then iterates over each log in logs. For each log:

    • It calculates the duration of the work log by subtracting prev from the ending time of the log.

    • If longest_duration is -1 (which means this is the first log being processed) or if the duration is greater than or equal to longest_duration, it updates ans:

      • If the duration is equal to longest_duration, it sets ans to the smaller of the current worker’s ID and the previous ans.

      • If the duration is greater than longest_duration, it sets ans to the current worker’s ID.

    • It updates longest_duration to the larger of the current longest_duration and the duration.

    • It updates prev to the ending time of the current log.

  3. After all logs have been processed, the function returns ans, which is the ID of the worker who has the longest continuous working duration.

The time complexity of this function is linear, O(n), as it makes a single pass over the logs. The space complexity is constant, O(1), as it doesn’t use any additional data structures.