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?- A. 7 0 5
- B. 7 1 5
- C. 5 0 5
- 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
- Problem: A sorted list of ticket prices is searched with Python's bisect module. python from bisect import bisectleft, bisectright a =…
- Problem: Orders (name, priority) are sorted by priority only, using Python's sorted with a key. python orders = [("ravi", 3), ("asha", 1)…
- Problem: A juice stall sells a ₹5 cup; customers pay with ₹5, ₹10 or ₹20 notes and the stall starts with no change. Decide whether every…
- Problem: Builds 1..100 are tested; every build from some version onward is broken. isbad() is expensive, so find the first bad build with…
- Problem: Sort values by increasing frequency; values with the same frequency go in decreasing order. python from collections import…
- Problem: A researcher's h-index is the largest h such that at least h papers have ≥ h citations each. python def hindex(c): c = sorted(c…