Data Structures & AlgorithmsVery hardProduct company OA

Problem: An employee's day is 'tiring' if they worked more than 8 hours. Find the longest run of consecutive days in which tiring days strictly outnumber non-tiring ones. Map days to +1/−1 and use first occurrences of prefix sums.

Problem: An employee's day is 'tiring' if they worked more than 8 hours. Find the longest run of consecutive days in which tiring days strictly outnumber non-tiring ones. Map days to +1/−1 and use first occurrences of prefix sums.
def longest_good(hours):
    first = {}; run = best = 0
    for i, h in enumerate(hours):
        run += 1 if h > 8 else -1
        if run > 0:
            best = i + 1
        else:
            if run not in first: first[run] = i
            if run - 1 in first: best = max(best, i - first[run - 1])
    return best
print(longest_good([6, 9, 6, 6, 10, 11, 6, 9, 5]), longest_good([6, 6, 7]), longest_good([9, 6, 6, 9, 9, 6, 6, 6]))
What is printed?
  1. A. 7 0 5
  2. B. 7 1 5
  3. C. 5 0 5
  4. D. 7 0 3

Correct answer: A. 7 0 5

We need a window with positive sum. If the prefix itself is positive, the whole prefix works. Otherwise, since prefix sums move in steps of ±1, the earliest prefix that is smaller than the current one is the first occurrence of run − 1. First list: prefixes −1, 0, −1, −2, −1, 0, −1, 0, −1; at i = 7 (prefix 0) the value −1 first appeared at i = 0 → days 1..7 (four tiring vs three) = 7. Third list: the prefix is 1 at i = 4 → 5. A positive-only sliding window fails because sums are not monotone. O(n).

More Coding Interview Problems questions

Exams that ask this topic