Find the earliest closing hour that minimizes a shop's penalty
Company: Stripe
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Other
Overview: Given an hourly log of whether customers showed up, choose the hour to close a shop so that empty open hours plus missed customer hours is as small as possible, and return the earliest such hour. Tests turning a brute-force scan into a one-pass incremental update and handling ties correctly.
Constraints
- 1 <= len(customers) <= 10^5
- customers consists only of the characters 'Y' and 'N'.
- The answer is an integer j with 0 <= j <= len(customers), so it is at most 10^5 and fits in a 32-bit signed integer.
Examples
Input: ('Y',)
Expected Output: 1
Explanation: Minimum valid, one 'Y' hour: staying open for it (j = 1) costs 0, closing at hour 0 costs 1.
Input: ('N',)
Expected Output: 0
Explanation: Minimum valid, one 'N' hour: closing at hour 0 costs 0, j = 1 costs 1.
Hints
- Closing at hour j splits the log into an open part (hours before j) and a closed part (hour j and later). Each part is charged for a different character.
- Both ends count: j = 0 (never open) and j = n (open for the whole log) are valid answers.
- Several hours can tie for the minimum penalty. Make sure your comparison keeps the earliest one.