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

The Employee That Worked on the Longest Task

Number: 2518

Difficulty: Easy

Paid? No

Companies: IBM, Morgan Stanley


Problem Description

Given a list of task logs where each log contains an employee id and the leave time of the task, determine which employee worked on the longest task. The first task starts at time 0 and each subsequent task starts immediately after the previous one ends. If multiple tasks share the longest duration, return the employee with the smallest id.


Key Insights

  • The first task's duration is its leave time because it starts at time 0.
  • For tasks after the first, the duration is the difference between the current task's leave time and the previous task's leave time.
  • Iterate through the logs, calculate each task's duration, and update the maximum duration found.
  • In case of a tie, choose the task with the smallest employee id.

Space and Time Complexity

Time Complexity: O(n), where n is the number of tasks, since we iterate through each log exactly once. Space Complexity: O(1), as we only use a few variables to track the maximum duration and employee id.


Solution

We iterate through the logs to compute the duration for each task. For the first task, the duration is simply its leave time since it starts at 0. For subsequent tasks, the duration is computed by subtracting the previous leave time from the current leave time. During the iteration, we keep track of the maximum duration and the corresponding employee id. If a task’s duration is equal to the current maximum, we update the employee id if the current id is smaller. This approach uses simple arithmetic operations and comparisons, ensuring an efficient and straightforward solution.


Code Solutions

# Function to find the employee who worked on the longest task
def hardestWorker(n, logs):
    # Initialize max_duration with the first task's duration
    max_duration = logs[0][1]
    employee_id = logs[0][0]

    # Loop through the logs starting from the second task
    for i in range(1, len(logs)):
        # Calculate current task duration
        current_duration = logs[i][1] - logs[i-1][1]
        # If current duration is greater than max_duration, update values
        if current_duration > max_duration:
            max_duration = current_duration
            employee_id = logs[i][0]
        # If current duration equals max_duration, choose the smaller id
        elif current_duration == max_duration:
            employee_id = min(employee_id, logs[i][0])
    return employee_id

# Example usage:
print(hardestWorker(10, [[0,3],[2,5],[0,9],[1,15]]))  # Expected output is 1
← Back to All Questions