Python 1124.py
class Solution:
def longestWPI(self, hours: List[int]) -> int:
result = 0
start = { 0: -1 }
total = 0
for i, h in enumerate(hours):
# plus one if tiring, else minus one
total += +1 if h > 8 else -1
# keep track of the first time we observe each value "total"
if total not in start:
start[total] = i
# longest interval with more tiring days
if total > 0: # right from the beginning
result = i + 1
if total - 1 in start: # number of tiring days is on larger than normal days
result = max(result, i - start[total - 1])
return result
Difficulty
and has an acceptance rate of about 38% (100k+ submissions).
Typical patterns to solve this problem:
- Array
- Hash Table
- Monotonic Stack
- Prefix Sum
- Stack
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 implementation solves the problem of finding the longest well-performing interval in a sequence of work hours. A day is considered “tiring” when the number of hours exceeds eight; otherwise it is “non-tiring”. The goal is to locate the maximum-length contiguous sub-array where the count of tiring days strictly exceeds the count of non-tiring days. The algorithm relies on a transformed prefix-sum representation and a hash map that records the earliest index at which each cumulative sum appears.
Key Steps
Initialization
result = 0
start = { 0: -1 }
total = 0
The variable result holds the length of the best interval discovered so far. The dictionary start maps each observed prefix sum to the first index where it occurs; it is seeded with the sum 0 at a virtual index -1 to simplify calculations that begin at the array start. The accumulator total tracks the running difference between tiring and non-tiring days.
Updating the Prefix Sum
for i, h in enumerate(hours):
total += +1 if h > 8 else -1
During the single pass over hours, each element contributes +1 for a tiring day or -1 for a non-tiring day. This conversion turns the original problem into one of locating sub-arrays whose transformed sum is positive.
Recording First Occurrences
if total not in start:
start[total] = i
Only the earliest index for each distinct total value is stored. Subsequent repetitions of the same sum are ignored, ensuring that later interval length calculations always reference the farthest possible left boundary.
Determining Candidate Intervals
if total > 0:
result = i + 1
if total - 1 in start:
result = max(result, i - start[total - 1])
Two scenarios are examined:
- When the cumulative sum is already positive (
total > 0), the interval from the beginning of the array up to the current index satisfies the condition, so the lengthi + 1becomes a candidate. - When
total - 1has been seen before, the sub-array that starts just after the earlier occurrence and ends at the current index has a net positive sum. The length of this interval isi - start[total - 1], andresultis updated if it exceeds the previous best.
Final Result
return result
After processing all elements, result contains the length of the longest well-performing interval, or 0 if none exists.
Edge Cases Handled
The algorithm gracefully manages an empty input list. Since the loop body never executes, result remains at its initial value of 0, which correctly indicates the absence of any interval.
When every day is non-tiring, the cumulative sum never becomes positive, and the condition total - 1 in start never holds because total stays at or below zero. Consequently, result stays 0, reflecting that no qualifying interval exists.
If all days are tiring, the cumulative sum increments by 1 on each iteration, staying positive throughout. The first conditional branch (total > 0) updates result to i + 1 on every step, ultimately yielding the full length of the input array as the answer.
Mixed sequences of tiring and non-tiring days are addressed by the combination of the two interval checks. The map of first occurrences guarantees that the algorithm can locate the earliest point where the prefix sum was one less than the current sum, thereby capturing the longest possible stretch where tiring days outnumber non-tiring days.
Performance Optimizations
The solution executes a single linear traversal of the input, performing only constant-time arithmetic and dictionary operations per element. By storing only the first index for each distinct prefix sum, the map avoids redundant entries, which reduces memory usage compared to a naïve approach that might record every occurrence. The use of a dictionary provides average-case constant-time lookups for both the existence check and retrieval of the stored index, enabling rapid evaluation of candidate intervals. The conditional expression for updating total eliminates the need for an explicit if-else block, streamlining the computation of the transformed prefix sum. Overall, the design balances time efficiency with modest auxiliary space, making it well-suited for large input sizes.
ELI5 - Simplified Explanation
Imagine that you are keeping track of a long playdate where some days are super active and some days are quiet. Each day you look at the clock to see if you played hard for more than eight hours. When the day is busy, you add one point to a score, and when the day is relaxed, you take one point away.
The computer starts at zero. Every time a new day passes, it updates the total score based on whether it was a busy day or a quiet day. The code keeps a little notebook called start to remember the very first time it reached a specific score. This is helpful because if the score ever gets higher than zero, it means there were more busy days than quiet days overall.
As it moves through each day, the computer checks two things to find the longest stretch of time where busy days won. First, it looks to see if the score is already above zero from the very start. If it is, the whole time you have been playing counts as a winning stretch. If the score is not above zero, the computer looks back at the notebook to see if a score that is exactly one point lower appeared before. If it finds that lower score, it calculates the distance between that moment and now. This distance is a segment where there were more busy days than quiet days. After checking these things, the computer saves the biggest stretch it has found so far and keeps going until the end of the list.
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 | C++ | Java | Python | TS | |||
| WalkCCC | C++ | Python | ||||||
| leetcode.ca | C++ | Java | Python | Go | ||||
| Progiez | C++ | Java | Python | |||||
| github | black-shadows | C++ | ||||||
| charles-wangkai | Java | |||||||
| everthis | JS | |||||||
| fsq | C++ | |||||||
| JoshCrozier | JS | |||||||
| lkwq007 | Python | |||||||
| suxrobGM | C# | |||||||
| varunu28 | Java | |||||||
| wisdompeak | C++ | |||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||
| WalkCCC | C++, Python | |||||||
| leetcode.ca | C++, Go, Java, Python | |||||||
| Progiez | C++, Java, Python | |||||||
| black-shadows | C++, C++ | |||||||
| charles-wangkai | Java | |||||||
| everthis | JavaScript | |||||||
| fsq | C++ | |||||||
| JoshCrozier | JavaScript | |||||||
| lkwq007 | Python | |||||||
| suxrobGM | C# | |||||||
| varunu28 | Java | |||||||
| wisdompeak | C++ |
Videos
Solved On The Same Day
- problem 1105: Filling Bookcase Shelves
- problem 1131: Maximum of Absolute Value Expression
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