Python 2432.py
class Solution:
def hardestWorker(self, n: int, logs: List[List[int]]) -> int:
result = 0
longest = 0
start = 0
for id, leave in logs:
duration = leave - start
if longest < duration or (longest == duration and result > id):
longest = duration
result = id
start = leave
return result
Difficulty
and has an acceptance rate of about 52% (80k+ submissions).
Typical patterns to solve this problem:
- Array
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided hardestWorker method determines which employee spent the longest uninterrupted period on a task, given a chronological list of log entries. Each log entry consists of an employee identifier and the time at which that employee finished a task. The algorithm walks through the logs once, computes the duration of each employee’s most recent task, and keeps track of the employee with the maximum duration. In the event of a tie, the employee with the smaller identifier is selected.
Key Steps
Initialization
result = 0
longest = 0
start = 0
Three variables are created before processing begins. result will hold the identifier of the employee with the longest task seen so far. longest stores the length of that task. start records the start time of the current interval, initially set to zero because the first task begins at time zero.
Iteration over the log entries
for id, leave in logs:
The method iterates over each pair [id, leave] in logs. The loop processes the entries in the order they appear, which is assumed to be chronological. This single-pass traversal eliminates the need for additional passes or sorting.
Duration calculation
duration = leave - start
For each entry, the elapsed time since the previous leave (or since time zero for the first entry) is computed. This subtraction yields the exact length of the task performed by the current employee.
Comparison and update
if longest < duration or (longest == duration and result > id):
longest = duration
result = id
The algorithm compares the newly computed duration with the current longest. If the new duration is greater, it becomes the new maximum and the corresponding employee identifier is stored in result. When the durations are equal, the secondary condition result > id ensures that the smaller identifier wins, satisfying the tie-breaking rule.
Advance the start marker
start = leave
After handling the current log entry, start is updated to the current leave time. This prepares the correct baseline for the next interval’s duration calculation.
Return the answer
return result
When all log entries have been examined, the method returns the identifier of the employee who worked the longest uninterrupted period.
Edge Cases Handled
When the log contains a single entry, the duration is computed as leave - 0, correctly reflecting the whole interval from the start of the timeline to the first leave time. The tie-breaking logic also works when multiple employees have identical durations; the condition result > id guarantees that the smallest identifier is chosen. If an employee’s task duration is zero (for example, when two consecutive logs have the same timestamp), the algorithm still processes the entry, but such a duration will never replace a positive longest value, preserving the correct maximum. The initialization of result to zero ensures that an employee with identifier zero can be selected if it truly has the longest duration, while still allowing any positive identifier to replace it when appropriate.
Performance Optimizations
The method achieves optimal efficiency by performing a single linear scan of the logs list. All calculations are done using primitive integer operations, and the algorithm maintains only three scalar variables (result, longest, start). This constant-space approach avoids allocating auxiliary data structures such as dictionaries or additional lists. By updating start in place after each iteration, the code eliminates the need for a separate array of start times, further reducing memory pressure. The conditional expression combines the primary comparison and the tie-breaking rule into one statement, minimizing branching overhead. Overall, the implementation delivers fast execution with minimal memory consumption, suitable for large input sizes.
ELI5 - Simplified Explanation
Imagine there is a busy workshop with several workers who take turns finishing their tasks throughout the day. This code is like a helper holding a clipboard to find out which person took the longest time to finish their own specific job.
The code starts by looking at a list that shows when each worker stopped their task. It keeps track of two things: which person did the job and how long they took.
First, the helper looks at the very first worker and sees how much time passed since the day began. Then, it moves to the next worker. Because each worker finishes their job at a different time, the code subtracts the finish time of the last task from the finish time of the current task to reveal how many minutes that specific worker spent working.
As the code goes through the list, it compares the current worker's time with the longest time recorded so far. If the current worker took even longer than anyone else, the helper erases the old name on the clipboard and writes down the new, slower worker's ID instead. If two people took the exact same amount of time, the helper picks the one with the smaller number ID to be safe. By the time the list is finished, the clipboard holds the ID of the person who spent the most time working.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | ||||||||||
|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | |||||||||
| www | AlgoMonster | Java | Python | C++ | TS | |||||
| WalkCCC | Java | Python | C++ | |||||||
| leetcode.ca | Java | Python | C++ | C | Go | Rust | TS | |||
| Progiez | Java | Python | C++ | |||||||
| github | charles-wangkai | Java | ||||||||
| everthis | JS | |||||||||
| fartem | Ruby | |||||||||
| fsq | C++ | |||||||||
| JoshCrozier | JS | |||||||||
| lkwq007 | Python | |||||||||
| varunu28 | Java | |||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||
| WalkCCC | C++, Python, Java | |||||||||
| leetcode.ca | C, C++, Go, Java, Python, Rust, TypeScript | |||||||||
| Progiez | C++, Java, Python | |||||||||
| charles-wangkai | Java | |||||||||
| everthis | JavaScript | |||||||||
| fartem | Ruby | |||||||||
| fsq | C++ | |||||||||
| JoshCrozier | JavaScript | |||||||||
| lkwq007 | Python | |||||||||
| varunu28 | Java |
Videos
Solved On The Same Day
- problem 1184: Distance Between Bus Stops
- problem 1342: Number of Steps to Reduce a Number to Zero
- problem 1399: Count Largest Group
- problem 1496: Path Crossing
- problem 1646: Get Maximum in Generated Array
- problem 1893: Check if All the Integers in a Range Are Covered
- problem 2404: Most Frequent Even Element
- problem 2451: Odd String Difference
- problem 2540: Minimum Common Value
- problem 609: Find Duplicate File in System
- problem 1169: Invalid Transactions
- problem 1711: Count Good Meals
- problem 1781: Sum of Beauty of All Substrings
- problem 1865: Finding Pairs With a Certain Sum
- problem 1871: Jump Game VII
- problem 2013: Detect Squares
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality