LeetCode 2432: The Employee That Worked on the Longest Task

Array

Problem Description

Explanation:

To solve this problem, we need to iterate over the given logs array and calculate the duration of each task for each employee. We can do this by keeping track of the current task end time for each employee. Then, we compare the duration of each task and find the one with the longest duration. If there is a tie, we return the employee with the smallest id.

  • We initialize a HashMap to store the end time of each task for each employee.
  • We iterate over the logs array and update the end time for each employee based on the current task.
  • We keep track of the employee with the longest task duration and the smallest id in case of a tie.
  • Finally, we return the employee with the longest task duration or the smallest id in case of a tie.

Time Complexity: O(n), where n is the number of tasks in the logs array. Space Complexity: O(n), to store the end time of tasks for each employee.

:

Solutions

class Solution {
    public int longestWorkingEmployee(int n, int[][] logs) {
        HashMap<Integer, Integer> taskEndTime = new HashMap<>();
        int longestDuration = 0;
        int longestEmployee = 0;
        
        for (int[] log : logs) {
            int employeeId = log[0];
            int endTime = log[1];
            int startTime = taskEndTime.getOrDefault(employeeId, 0);
            int duration = endTime - startTime;
            
            if (duration > longestDuration || (duration == longestDuration && employeeId < longestEmployee)) {
                longestDuration = duration;
                longestEmployee = employeeId;
            }
            
            taskEndTime.put(employeeId, endTime);
        }
        
        return longestEmployee;
    }
}

Loading editor...