The Employee That Worked on the Longest Task - 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:

  • idi is the id of the employee that worked on the ith task, and
  • leaveTimei is the time at which the employee finished the ith task. All the values leaveTimei are 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.

Input & Output

Example 1 — Basic Case
$ Input: logs = [[0,3],[2,5],[0,9],[1,15]]
Output: 1
💡 Note: Task durations: [3-0=3, 5-3=2, 9-5=4, 15-9=6]. Employee 1 worked the longest task (6 time units).
Example 2 — Tie Breaking
$ Input: logs = [[1,1],[2,3],[3,4]]
Output: 1
💡 Note: Task durations: [1-0=1, 3-1=2, 4-3=1]. Employee 2 has the longest task (2 time units).
Example 3 — Same Duration Different IDs
$ Input: logs = [[2,4],[1,7],[3,8]]
Output: 1
💡 Note: Task durations: [4-0=4, 7-4=3, 8-7=1]. Employee 2 worked the longest task (4 time units).

Constraints

  • 1 ≤ logs.length ≤ 500
  • logs[i].length == 2
  • 0 ≤ idi ≤ 499
  • 1 ≤ leaveTimei ≤ 500
  • idi != idi+1
  • leaveTimei are sorted in a strictly increasing order

Visualization

Tap to expand
The Employee That Worked on the Longest Task INPUT logs = [[0,3],[2,5],[0,9],[1,15]] Index ID Leave 0 0 3 1 2 5 2 0 9 3 1 15 Timeline View E0 E2 E0 E1 0 3 5 9 15 n = 4 employees (IDs: 0-3) ALGORITHM STEPS 1 Initialize maxTime=0, result=-1, prev=0 2 Calculate Duration duration = leaveTime - prev 3 Update Max If duration > maxTime or tie 4 Return Result Return employee with longest i ID Dur Max Result 0 0 3 3 0 1 2 2 3 0 2 0 4 4 0 3 1 6 6 1 15 - 9 = 6 (longest!) FINAL RESULT Employee with Longest Task: Employee ID 1 Task Duration: 6 units All Task Durations: E0:3 E2:2 E0:4 E1:6 OK Output: 1 Key Insight: Single pass O(n) solution: Track previous leave time to calculate each task's duration. Duration = current_leaveTime - previous_leaveTime. First task starts at time 0. For ties (equal duration), keep the smaller employee ID by checking (duration > maxTime) OR (duration == maxTime AND id is smaller). TutorialsPoint - The Employee That Worked on the Longest Task | Single Pass Optimization
Asked in
Amazon 12 Apple 8
12.5K Views
Medium Frequency
~15 min Avg. Time
485 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen