LeetCode solutions

1219. Longest Well-Performing Interval

My accepted Python solution to LeetCode problem 1219, Longest Well-Performing Interval, running in 19ms.

  • Difficulty: Medium
  • Python
  • Runtime 19ms
  • Memory 17.8MB

Read the problem on LeetCode View on GitHub

Python

Accepted on LeetCode — runtime 19ms, memory 17.8MB, accepted 2026-01-02.

python
class Solution:
    def longestWPI(self, hours: List[int]) -> int:
        # Transform: >8 hours = 1, <=8 hours = -1
        # Find longest subarray with sum > 0
        
        prefix_sum = 0
        first_occurrence = {}  # Maps prefix_sum to first index
        result = 0
        
        for i, h in enumerate(hours):
            prefix_sum += 1 if h > 8 else -1
            
            if prefix_sum > 0:
                # From start to current index is valid
                result = i + 1
            else:
                # Look for prefix_sum - 1 (we need sum > 0, so current - prev > 0)
                if prefix_sum - 1 in first_occurrence:
                    result = max(result, i - first_occurrence[prefix_sum - 1])
            
            if prefix_sum not in first_occurrence:
                first_occurrence[prefix_sum] = i
        
        return result

Source