Leetcode 2432: The Employee That Worked on the Longest Task

grid47
grid47
Exploring patterns and algorithms
Mar 8, 2024 6 min read

You are given a group of employees, each identified by a unique ID. A series of tasks have been completed, where each task has a specific start and end time. Your task is to identify which employee worked the longest on a task. If there is a tie between multiple employees, return the one with the smallest ID. The time for each task is calculated by subtracting the start time from the end time, and each task starts right after the previous one ends.
Problem
Approach
Steps
Complexity
Input: You are given two inputs: n (the total number of employees) and logs (a 2D array where each element logs[i] = [idi, leaveTimei], representing the ID of the employee and the time they finished the task).
Example: n = 5, logs = [[0,3],[1,7],[2,10],[0,15],[3,20]]
Constraints:
• 2 <= n <= 500
• 1 <= logs.length <= 500
• logs[i].length == 2
• 0 <= idi <= n - 1
• 1 <= leaveTimei <= 500
• logs are sorted in strictly increasing order of leaveTimei
Output: Return the ID of the employee who worked the longest on a task. If there is a tie, return the smallest ID.
Example: Output: 0
Constraints:
• There will always be a unique solution.
Goal: The goal is to determine the employee who worked the longest by calculating the time each employee spent on tasks, then selecting the employee with the maximum task time.
Steps:
• 1. Initialize variables to track the end time of the last task, the maximum task duration, and the employee ID.
• 2. Iterate through each task in logs and calculate the duration of each task.
• 3. Compare the duration of the current task with the maximum and update the employee ID accordingly, ensuring that ties are broken by selecting the smallest ID.
• 4. Return the ID of the employee with the longest task duration.
Goal: The solution should be efficient given the constraints.
Steps:
• Ensure the algorithm processes each task in logs efficiently.
• Handle edge cases where multiple employees have the same task duration.
Assumptions:
• The leaveTime for each task is unique.
• Each employee works on at least one task.
Input: n = 5, logs = [[0,3],[1,7],[2,10],[0,15],[3,20]]
Explanation: In this case, the employee tasks are as follows: Task 0: [0, 3] (duration 3), Task 1: [1, 7] (duration 6), Task 2: [2, 10] (duration 3), Task 3: [0, 15] (duration 12), Task 4: [3, 20] (duration 5). The employee with ID 0 worked the longest (12 units), so the output is 0.

Input: n = 4, logs = [[0,4],[1,6],[0,9],[2,15]]
Explanation: Here, the tasks are: Task 0: [0, 4] (duration 4), Task 1: [1, 6] (duration 2), Task 2: [0, 9] (duration 5), Task 3: [2, 15] (duration 6). The longest task duration is 6 units, and employee with ID 2 worked the longest, so the output is 2.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus