The Employee That Worked on the Longest Task solution and explanation
9 more videos on this problem
The Employee that worked on the longest task - Leetcode Weekly Contest 314Gopala Krishna Reddy Maguluri · 0:21 · 593 views
The Employee That Worked on the Longest Task | leetcode Weekly 314 | Leetcode EasyBinaryMagic · 10:02 · 409 views
Leetcode Weekly contest 314 - Easy - The Employee That Worked on the Longest TaskPrakhar Agrawal · 6:40 · 305 views
2432. The Employee That Worked on the Longest Task (Leetcode Easy)Programming Live with Larry · 3:59 · 287 views
The Employee That Worked on the Longest Task || LeetCode Weekly Contest 314 || C++Priyanshi Porwal · 4:46 · 223 views
2432. The Employee That Worked on the Longest Task || Leetcode Contest Easy ||Array || CPPCoding Techniques with Komal | Newton School · 14:56 · 145 views
Leetcode 2432. The Employee That Worked on the Longest TaskElite Code · 6:17 · 140 views
2432. The Employee That Worked on the Longest Task||Leetcode weekly contest314||Code in descriptionCS warriors · 6:54 · 115 views
LeetCode 2432 | The Employee That Worked on the Longest Task | Math | JavaSleepy Cracker · 3:28 · 106 views
leetcode 2432. The Employee That Worked on the Longest Task - linear scanCode-Yao · 5:50 · 105 views
The problem
There are n employees, each with a unique id from 0 to n - 1.
You are given a 2D integer array logs where logs[i] = [idi, leaveTimei] where:
idiis the id of the employee that worked on theithtask, andleaveTimeiis the time at which the employee finished theithtask. All the valuesleaveTimeiare unique.
Note that the ith task starts the moment right after the (i - 1)th task ends, and the 0th task starts at time 0.
Return the id of the employee that worked the task with the longest time. If there is a tie between two or more employees, return the smallest id among them.
Example 1:
Input: n = 10, logs = [[0,3],[2,5],[0,9],[1,15]] Output: 1 Explanation: Task 0 started at 0 and ended at 3 with 3 units of times. Task 1 started at 3 and ended at 5 with 2 units of times. Task 2 started at 5 and ended at 9 with 4 units of times. Task 3 started at 9 and ended at 15 with 6 units of times. The task with the longest time is task 3 and the employee with id 1 is the one that worked on it, so we return 1.
Example 2:
Input: n = 26, logs = [[1,1],[3,7],[2,12],[7,17]] Output: 3 Explanation: Task 0 started at 0 and ended at 1 with 1 unit of times. Task 1 started at 1 and ended at 7 with 6 units of times. Task 2 started at 7 and ended at 12 with 5 units of times. Task 3 started at 12 and ended at 17 with 5 units of times. The tasks with the longest time is task 1. The employee that worked on it is 3, so we return 3.
Example 3:
Input: n = 2, logs = [[0,10],[1,20]] Output: 0 Explanation: Task 0 started at 0 and ended at 10 with 10 units of times. Task 1 started at 10 and ended at 20 with 10 units of times. The tasks with the longest time are tasks 0 and 1. The employees that worked on them are 0 and 1, so we return the smallest id 0.
Constraints:
2 <= n <= 5001 <= logs.length <= 500logs[i].length == 20 <= idi <= n - 11 <= leaveTimei <= 500idi != idi+1leaveTimeiare sorted in a strictly increasing order.
Approach overview
Problem Overview: You receive a list of logs where logs[i] = [employeeId, leaveTime]. Tasks are executed sequentially, and each employee works on exactly one task at a time. The duration of a task is the difference between the current leaveTime and the previous task's finish time. Your goal is to find the employee who worked on the longest single task. If multiple employees have the same longest duration, return the smallest employee ID.
The logs are already sorted by completion time. That means you can process them in order and compute each task's duration using the difference between consecutive timestamps. The problem mainly tests careful array traversal and comparison logic using basic operations on a array.
Approach 1: Iterative Comparison Approach (O(n) time, O(1) space)
Traverse the log array once while tracking the previous task's finish time. For each log entry, compute the task duration using duration = leaveTime - previousLeave. Maintain two variables: the maximum duration seen so far and the employee ID associated with that duration. When a new duration exceeds the current maximum, update both values. If the duration ties with the maximum, choose the smaller employee ID. Since the logs are processed sequentially, a single pass is enough. This approach uses constant extra memory and relies purely on comparisons and arithmetic.
This technique is essentially a simple simulation of the execution timeline. Because each duration depends only on the previous timestamp, you don't need additional structures beyond a few variables. Many interview problems involving sequential events follow this exact pattern of "compute difference and track best".
Approach 2: Prefix Sum Optimization (O(n) time, O(n) space)
Another way to structure the logic is to explicitly store task durations using a prefix-difference idea. First iterate through the logs and compute an auxiliary array where duration[i] = logs[i][1] - logs[i-1][1] (with the first duration being logs[0][1]). Once durations are precomputed, perform a second pass to find the maximum duration and apply the same tie-breaking rule for employee IDs. This approach separates duration calculation from comparison logic, which can make debugging easier in some cases.
The method borrows the idea behind prefix sum transformations: convert cumulative timestamps into per-task durations so each entry becomes independent. However, the extra array means additional O(n) space, which is unnecessary for this problem.
Recommended for interviews: The iterative comparison approach is the expected solution. It runs in O(n) time with O(1) space and demonstrates that you understand how to derive task durations from sequential timestamps. Showing the brute reasoning (difference between consecutive times) first and then implementing the single-pass comparison proves strong fundamentals in array traversal and event timeline problems.
Approach 1: Iterative Comparison Approach
The idea is to iterate through the logs and calculate the time taken for each task. The task time is calculated as the difference between the leave time of the current task and the leave time of the previous task. We keep track of the maximum task time and the corresponding employee ID. If a task time is longer than the current maximum, or if it is equal but the ID is smaller, we update our records.
from typing import List
def longestTaskEmployee(n: int, logs: List[List[int]]) -> int:
max_time = 0
max_id = logs[0][0]
for i in range(len(logs)):
current_time = logs[i][1] - (0 if i == 0 else logs[i-1][1])
if current_time > max_time or (current_time == max_time and logs[i][0] < max_id):
max_time = current_time
max_id = logs[i][0]
return max_id
# Example usage
n = 10
logs = [[0, 3], [2, 5], [0, 9], [1, 15]]
print(longestTaskEmployee(n, logs))import java.util.List;
class Solution {
public int longestTaskEmployee(int n, int[][] logs) {
int maxTime = 0;
int maxId = logs[0][0];
for (int i = 0; i < logs.length; i++) {
int currentTime = logs[i][1] - (i == 0 ? 0 : logs[i-1][1]);
if (currentTime > maxTime || (currentTime == maxTime && logs[i][0] < maxId)) {
maxTime = currentTime;
maxId = logs[i][0];
}
}
return maxId;
}
public static void main(String[] args) {
Solution sol = new Solution();
int[][] logs = {{0, 3}, {2, 5}, {0, 9}, {1, 15}};
int result = sol.longestTaskEmployee(10, logs);
System.out.println(result);
}
}#include <vector>
class Solution {
public:
int longestTaskEmployee(int n, std::vector<std::vector<int>>& logs) {
int maxTime = 0;
int maxId = logs[0][0];
for (int i = 0; i < logs.size(); i++) {
int currentTime = logs[i][1] - (i == 0 ? 0 : logs[i-1][1]);
if (currentTime > maxTime || (currentTime == maxTime && logs[i][0] < maxId)) {
maxTime = currentTime;
maxId = logs[i][0];
}
}
return maxId;
}
};
int main() {
Solution s;
std::vector<std::vector<int>> logs = {{0, 3}, {2, 5}, {0, 9}, {1, 15}};
int result = s.longestTaskEmployee(10, logs);
std::cout << result;
return 0;
}function longestTaskEmployee(n, logs) {
let maxTime = 0;
let maxId = logs[0][0];
for (let i = 0; i < logs.length; i++) {
let currentTime = logs[i][1] - (i === 0 ? 0 : logs[i-1][1]);
if (currentTime > maxTime || (currentTime === maxTime && logs[i][0] < maxId)) {
maxTime = currentTime;
maxId = logs[i][0];
}
}
return maxId;
}
// Example usage
let n = 10;
let logs = [[0, 3], [2, 5], [0, 9], [1, 15]];
console.log(longestTaskEmployee(n, logs));#include <stdio.h>
int longestTaskEmployee(int n, int logs[][2], int logsSize) {
int maxTime = 0;
int maxId = logs[0][0];
for (int i = 0; i < logsSize; i++) {
int currentTime = logs[i][1] - (i == 0 ? 0 : logs[i-1][1]);
if (currentTime > maxTime || (currentTime == maxTime && logs[i][0] < maxId)) {
maxTime = currentTime;
maxId = logs[i][0];
}
}
return maxId;
}
int main() {
int logs[][2] = {{0, 3}, {2, 5}, {0, 9}, {1, 15}};
int n = 10;
int result = longestTaskEmployee(n, logs, 4);
printf("%d", result);
return 0;
}using System;
public class Solution {
public int LongestTaskEmployee(int n, int[][] logs) {
int maxTime = 0;
int maxId = logs[0][0];
for (int i = 0; i < logs.Length; i++) {
int currentTime = logs[i][1] - (i == 0 ? 0 : logs[i-1][1]);
if (currentTime > maxTime || (currentTime == maxTime && logs[i][0] < maxId)) {
maxTime = currentTime;
maxId = logs[i][0];
}
}
return maxId;
}
public static void Main(string[] args) {
var sol = new Solution();
int[][] logs = { new int[]{0, 3}, new int[]{2, 5}, new int[]{0, 9}, new int[]{1, 15} };
Console.WriteLine(sol.LongestTaskEmployee(10, logs));
}
}The function longestTaskEmployee processes each task by calculating its duration from start and compares with the current maximum. The employee ID is recorded if it's either longer or ties with a smaller ID.
Time Complexity: O(m), requires looping over all logs.
Space Complexity: O(1), no extra storage apart from variables.
Approach 2: Prefix Sum Optimization
Although not much optimization can be done beyond iterating to find the longest task, another approach involves using prefix sums or cumulative sums of timings to quickly query the execution time of any task. However, since the nature of the task list is linear, this provides similar performance in practice.
def longestTaskEmployeeOptimized(n, logs):
cumulative_time = 0
max_time = 0
max_id = 0
for log in logs:
task_time = log[1] - cumulative_time
if task_time > max_time or (task_time == max_time and log[0] < max_id):
max_time = task_time
max_id = log[0]
cumulative_time = log[1]
return max_id
# Example usage
n = 26
logs = [[1, 1], [3, 7], [2, 12], [7, 17]]
print(longestTaskEmployeeOptimized(n, logs))class Solution {
public int longestTaskEmployeeOptimized(int n, int[][] logs) {
int cumulativeTime = 0;
int maxTime = 0;
int maxId = 0;
for (int[] log : logs) {
int taskTime = log[1] - cumulativeTime;
if (taskTime > maxTime || (taskTime == maxTime && log[0] < maxId)) {
maxTime = taskTime;
maxId = log[0];
}
cumulativeTime = log[1];
}
return maxId;
}
public static void main(String[] args) {
Solution sol = new Solution();
int[][] logs = {{1, 1}, {3, 7}, {2, 12}, {7, 17}};
System.out.println(sol.longestTaskEmployeeOptimized(4, logs));
}
}#include <vector>
#include <map>
class Solution {
public:
int longestTaskEmployeeOptimized(int n, std::vector<std::vector<int>>& logs) {
int cumulativeTime = 0;
int maxTime = 0;
int maxId = 0;
for (const auto& log : logs) {
int taskTime = log[1] - cumulativeTime;
if (taskTime > maxTime || (taskTime == maxTime && log[0] < maxId)) {
maxTime = taskTime;
maxId = log[0];
}
cumulativeTime = log[1];
}
return maxId;
}
};
int main() {
Solution s;
std::vector<std::vector<int>> logs = {{1, 1}, {3, 7}, {2, 12}, {7, 17}};
int result = s.longestTaskEmployeeOptimized(4, logs);
std::cout << result;
return 0;
}function longestTaskEmployeeOptimized(n, logs) {
let cumulativeTime = 0;
let maxTime = 0;
let maxId = 0;
for (let log of logs) {
let taskTime = log[1] - cumulativeTime;
if (taskTime > maxTime || (taskTime === maxTime && log[0] < maxId)) {
maxTime = taskTime;
maxId = log[0];
}
cumulativeTime = log[1];
}
return maxId;
}
// Example usage
let n = 26;
let logs = [[1, 1], [3, 7], [2, 12], [7, 17]];
console.log(longestTaskEmployeeOptimized(n, logs));#include <stdio.h>
int longestTaskEmployeeOptimized(int n, int logs[][2], int logsSize) {
int cumulativeTime = 0;
int maxTime = 0;
int maxId = 0;
for (int i = 0; i < logsSize; i++) {
int taskTime = logs[i][1] - cumulativeTime;
if (taskTime > maxTime || (taskTime == maxTime && logs[i][0] < maxId)) {
maxTime = taskTime;
maxId = logs[i][0];
}
cumulativeTime = logs[i][1];
}
return maxId;
}
int main() {
int logs[][2] = {{1, 1}, {3, 7}, {2, 12}, {7, 17}};
int n = 4;
int result = longestTaskEmployeeOptimized(n, logs, 4);
printf("%d", result);
return 0;
}public class Solution {
public int LongestTaskEmployeeOptimized(int n, int[][] logs) {
int cumulativeTime = 0;
int maxTime = 0;
int maxId = 0;
foreach (var log in logs) {
int taskTime = log[1] - cumulativeTime;
if (taskTime > maxTime || (taskTime == maxTime && log[0] < maxId)) {
maxTime = taskTime;
maxId = log[0];
}
cumulativeTime = log[1];
}
return maxId;
}
public static void Main(string[] args) {
var sol = new Solution();
int[][] logs = { new int[] {1, 1}, new int[] {3, 7}, new int[] {2, 12}, new int[] {7, 17} };
Console.WriteLine(sol.LongestTaskEmployeeOptimized(26, logs));
}
}The Python solution here uses cumulative task conclusion time to determine task length, similar to prefix sum operations, ensuring a single linear pass for efficiency.
Time Complexity: O(m), where m is the number of log entries.
Space Complexity: O(1), uses only a few local variables.
Approach 3: Direct Traversal
We use a variable last to record the end time of the last task, a variable mx to record the longest working time, and a variable ans to record the employee with the longest working time and the smallest id. Initially, all three variables are 0.
Next, we traverse the array logs. For each employee, we subtract the end time of the last task from the time the employee completes the task to get the working time t of this employee. If mx is less than t, or mx equals t and the id of this employee is less than ans, then we update mx and ans. Then we update last to be the end time of the last task plus t. Continue to traverse until the entire array is traversed.
Finally, return the answer ans.
The time complexity is O(n), where n is the length of the array logs. The space complexity is O(1).
function hardestWorker(n: number, logs: number[][]): number {
let [ans, mx, last] = [0, 0, 0];
for (let [uid, t] of logs) {
t -= last;
if (mx < t || (mx == t && ans > uid)) {
ans = uid;
mx = t;
}
last += t;
}
return ans;
}func hardestWorker(n int, logs [][]int) (ans int) {
var mx, last int
for _, log := range logs {
uid, t := log[0], log[1]
t -= last
if mx < t || (mx == t && uid < ans) {
mx = t
ans = uid
}
last += t
}
return
}impl Solution {
pub fn hardest_worker(n: i32, logs: Vec<Vec<i32>>) -> i32 {
let mut res = 0;
let mut max = 0;
let mut pre = 0;
for log in logs.iter() {
let t = log[1] - pre;
if t > max || (t == max && res > log[0]) {
res = log[0];
max = t;
}
pre = log[1];
}
res
}
}Approach 4: Default Approach
impl Solution {
pub fn hardest_worker(n: i32, logs: Vec<Vec<i32>>) -> i32 {
let mut ans = 0;
let mut mx = 0;
let mut last = 0;
for log in logs {
let uid = log[0];
let t = log[1];
let diff = t - last;
last = t;
if diff > mx || (diff == mx && uid < ans) {
ans = uid;
mx = diff;
}
}
ans
}
}Complexity comparison
| Approach | Complexity |
|---|---|
| Iterative Comparison Approach | Time Complexity: O(m), requires looping over all logs. |
| Prefix Sum Optimization | Time Complexity: O(m), where m is the number of log entries. |
| Direct Traversal | – |
| Default Approach | – |
Complexity analysis
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Iterative Comparison Approach | O(n) | O(1) | Best general solution. Single pass over the logs with constant memory. |
| Prefix Sum Optimization | O(n) | O(n) | Useful when you want explicit duration storage or easier debugging of intermediate values. |
Frequently asked questions
Is The Employee That Worked on the Longest Task easy or hard?
The problem is classified as Easy on LeetCode with an acceptance rate around 50%. It focuses on careful iteration and handling edge cases such as tie-breaking when multiple employees have the same longest task duration.
The Employee That Worked on the Longest Task Python/Java solution
Python, Java, C++, and JavaScript solutions all follow the same logic: iterate through the logs, compute duration differences, and update the maximum duration with tie-breaking by employee ID. The algorithm remains O(n) time and O(1) space regardless of language.
How to solve The Employee That Worked on the Longest Task in O(n)?
Iterate through the logs while keeping the previous leave time. For each entry, compute the task duration as the difference between the current and previous timestamp. Update the maximum duration and employee ID when a longer task appears or when a tie requires selecting the smaller ID. This requires one pass through the array.
What is the best approach for The Employee That Worked on the Longest Task?
The best approach is a single-pass iterative comparison over the logs. Compute each task's duration using the difference between consecutive leave times and track the maximum duration. If two durations tie, return the smaller employee ID. This solution runs in O(n) time and O(1) space.
Is The Employee That Worked on the Longest Task asked at Google/Amazon/Meta?
Problems like this appear in interviews at companies such as Amazon, Google, and Meta because they test basic event processing and array traversal. Candidates are expected to compute differences between timestamps and track optimal values efficiently.
What data structure is used in The Employee That Worked on the Longest Task?
The problem primarily uses an array of log entries. Each entry contains an employee ID and a timestamp, and the algorithm processes the array sequentially to compute durations and determine the maximum task time.
What is the time complexity of The Employee That Worked on the Longest Task?
The optimal solution runs in O(n) time because each log entry is processed exactly once. Only a few variables are maintained during traversal, so the space complexity is O(1).
