Minimum Penalty for a Shop - Problem

You are given the customer visit log of a shop represented by a 0-indexed string customers consisting only of characters 'N' and 'Y':

  • If the ith character is 'Y', it means that customers come at the ith hour
  • If the ith character is 'N', it means that no customers come at the ith hour

If the shop closes at the jth hour (0 ≤ j ≤ n), the penalty is calculated as follows:

  • For every hour when the shop is open and no customers come, the penalty increases by 1
  • For every hour when the shop is closed and customers come, the penalty increases by 1

Return the earliest hour at which the shop must be closed to incur a minimum penalty.

Note: If a shop closes at the jth hour, it means the shop is closed at the hour j.

Input & Output

Example 1 — Basic Case
$ Input: customers = "YYNY"
Output: 2
💡 Note: Closing at hour 2 gives penalty of 1: open during hours 0,1 (both Y, no penalty) and closed during hours 2,3 (one Y at hour 3, penalty=1)
Example 2 — All Customers
$ Input: customers = "YYYY"
Output: 4
💡 Note: Best to stay open all hours (close at hour 4): no penalty for being open with customers, penalty=0
Example 3 — No Customers
$ Input: customers = "NNNN"
Output: 0
💡 Note: Best to close immediately (hour 0): no penalty for being closed when no customers come, penalty=0

Constraints

  • 1 ≤ customers.length ≤ 105
  • customers consists only of characters 'Y' and 'N'

Visualization

Tap to expand
Minimum Penalty for a Shop INPUT customers = "YYNY" Y i=0 Y i=1 N i=2 Y i=3 Y = Customer comes N = No customer Penalty Rules: Open + No customer = +1 Closed + Customer = +1 n = 4 (string length) Close hours: 0, 1, 2, 3, 4 ALGORITHM STEPS 1 Count total Y's Total Y = 3 (penalty if close at hour 0) 2 Track running penalty Adjust as we move closing hour right 3 Calculate each hour Hour Char Penalty Min? 0 - 3 No 1 Y 2 No 2 Y 1 OK 3 N 2 No 4 Y 1 No 4 Return earliest min Hour 2 has penalty = 1 (first occurrence) FINAL RESULT Close shop at hour 2 Shop Timeline OPEN h=0 OPEN h=1 CLOSE h=2 CLOSE h=3 Close here! Penalty Breakdown Hours 0-1 (Open): Y, Y -- Customers came Penalty: 0 Hours 2-3 (Closed): N -- No customer (OK) Y -- Customer came (+1) Penalty: 1 Output: 2 Key Insight: Use prefix sum approach: Start with penalty = total Y's (all customers missed if close at 0). Moving closing hour right: Y decreases penalty (now served), N increases penalty (open but empty). Time complexity: O(n), Space complexity: O(1). Track minimum penalty and its earliest position. TutorialsPoint - Minimum Penalty for a Shop | Optimal Solution
Asked in
Amazon 15 Google 12 Microsoft 8
23.5K Views
Medium Frequency
~15 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