Longest Well-Performing Interval - Problem

We are given hours, a list of the number of hours worked per day for a given employee.

A day is considered to be a tiring day if and only if the number of hours worked is strictly greater than 8.

A well-performing interval is an interval of days for which the number of tiring days is strictly larger than the number of non-tiring days.

Return the length of the longest well-performing interval.

Input & Output

Example 1 — Basic Well-Performing Interval
$ Input: hours = [9,9,6,0,6,6,9]
Output: 3
💡 Note: The longest well-performing interval is [9,9,6] from index 0 to 2. It has 2 tiring days (9>8, 9>8) and 1 non-tiring day (6≤8), so tiring > non-tiring.
Example 2 — No Well-Performing Interval
$ Input: hours = [6,6,6]
Output: 0
💡 Note: All days have ≤8 hours, so no interval can have more tiring days than non-tiring days. The longest well-performing interval has length 0.
Example 3 — Entire Array is Well-Performing
$ Input: hours = [9,9,9]
Output: 3
💡 Note: All days are tiring (>8 hours), so the entire array [9,9,9] is well-performing with 3 tiring days and 0 non-tiring days.

Constraints

  • 1 ≤ hours.length ≤ 104
  • 0 ≤ hours[i] ≤ 16

Visualization

Tap to expand
Longest Well-Performing Interval INPUT hours = [9, 9, 6, 0, 6, 6, 9] 0 1 2 3 4 5 6 9 9 6 0 6 6 9 Tiring (greater than 8) Non-tiring (8 or less) Transform to scores: Tiring = +1, Non-tiring = -1 +1 +1 -1 -1 -1 -1 +1 Prefix sums: 1 2 1 0 -1 -2 -1 ALGORITHM STEPS 1 Transform hours Convert to +1 (tiring) or -1 (non-tiring) 2 Compute prefix sum Track running total of transformed values 3 Use HashMap Store first occurrence of each prefix sum 4 Find longest interval If sum greater than 0: length = i+1 Else: find sum-1 in map HashMap (first index of sum): sum: 1 --> index: 0 sum: 2 --> index: 1 sum: -1 --> index: 4 sum: -2 --> index: 5 FINAL RESULT Longest Well-Performing Interval: 9 9 6 0 6 6 Interval: [9, 9, 6] Tiring days: 2 Non-tiring days: 1 2 > 1 ... OK! Output: 3 Length of longest interval where tiring > non-tiring ... OK Key Insight: Transform to +1/-1 and use prefix sums. A well-performing interval [i,j] means sum(i to j) > 0. If prefix[j] > 0, interval [0,j] is valid. Otherwise, find earliest index where prefix was (prefix[j]-1). HashMap stores first occurrence of each prefix sum for O(n) time complexity. TutorialsPoint - Longest Well-Performing Interval | Hash Approach
Asked in
Google 25 Amazon 18 Microsoft 15 Facebook 12
32.0K Views
Medium Frequency
~25 min Avg. Time
892 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