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
Shop Penalty Calculation: customers = "YYNY"YYNYHour 0Hour 1Hour 2Hour 3OPEN (penalty for N)CLOSED(penalty for Y)Closing at hour 2: Open penalty = 0, Closed penalty = 1Total Penalty = 1, Answer = 2
Understanding the Visualization
1
Input
Customer log string with Y (customer) and N (no customer)
2
Process
Calculate penalty for each closing hour
3
Output
Earliest hour with minimum penalty
Key Takeaway
🎯 Key Insight: Penalty changes predictably as closing hour moves right: lose N penalties, gain Y penalties
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