Minimum Penalty for a Shop
Problem Statement
A shop keeps a log of n hours as a string customers. customers[i] is 'Y' if customers came during hour i, and 'N' if nobody came.
You must pick a closing hour j, where 0 ≤ j ≤ n. The shop is open during hours 0 … j−1 and closed from hour j onward. Choosing j = n means it stays open for every hour.
The penalty for closing at j is:
+1for every open hour with'N'(open, but nobody came), and+1for every closed hour with'Y'(closed, but customers came).
Return the closing hour with the smallest penalty. If several hours tie, return the earliest one.
A string customers of length n made of the characters 'Y' and 'N'.
One integer j in [0, n]: the earliest closing hour with the minimum penalty.
Penalties for j = 0, 1, 2, 3, 4 are 3, 2, 1, 2, 1. The minimum is 1, first reached at j = 2 (open for YY, closed for NY: one missed Y).
Nobody ever comes, so closing right away costs 0.
Customers come every hour, so the best is to stay open the whole time: j = n = 4.
- • 1 ≤ n ≤ 10^5
- • customers contains only 'Y' and 'N'.
Pattern Recognition Clues
Recognising these key signals in the problem description immediately identifies the pattern:
Approach Complexity Ladder
For each j in 0..n, count 'N' before j and 'Y' from j onward
Build N-counts from the left and Y-counts from the right, then add them per hour
Start at penalty = total Y, then ±1 per hour as the closing time moves right
Try every closing hour j from 0 to n. Count the 'N' in customers[0 … j−1] and the 'Y' in customers[j … n−1]. Keep the first j with the smallest total.
Recognition rule for this sub-pattern:
Unlock Complete Visual Walkthrough & Optimal C++
The interactive animated dry-run player, optimized C++ implementation, state invariant derivations, and edge-case breakdown for this question are part of Brute2Best Pro. The anchor question of every sub-pattern is completely free.
First anchor question per pattern, Part 1 LLD & Module 1 C++ basics are 100% Free forever.
How this concept connects to System Design & C++ Systems
Top engineering interviews test whether you understand how algorithms like Prefix Sum translate into production architectures and low-level memory mechanics.
Foundations: Object-Oriented Principles in C++23
Class invariants, pure virtual interfaces, and RAII smart pointers.
Food Delivery System (Zomato Architecture)
Real-world machine coding application of algorithms and design patterns.
Pointers vs References Deep Dive
Pointer arithmetic and memory layout under the hood.
Virtual Method Table (vtable) & Memory Layout
Polymorphism, vptr overhead, and multiple inheritance in memory.