Find Good Days to Rob the Bank - Problem

You and your gang are planning to rob a bank! 🏦 To ensure a successful heist, you need to carefully analyze the security patterns over time.

You're given an array security where security[i] represents the number of guards on duty on day i. You also have a parameter time that defines your observation window.

A day is considered "good" for robbing if:

  • There are at least time days before AND after this day (so you have enough data)
  • For the time days leading up to this day, security is non-increasing (guards are getting lazy or leaving)
  • For the time days after this day, security is non-decreasing (guards are ramping back up)

In other words, you want to rob when security is at a local minimum with consistent patterns on both sides!

Goal: Return all the good days to rob the bank (0-indexed). The order doesn't matter.

Input & Output

example_1.py β€” Basic Valley Pattern
$ Input: security = [5,3,3,3,5,6,2], time = 2
β€Ί Output: [2, 3]
πŸ’‘ Note: Day 2: Security goes 5β†’3β†’3β†’3β†’5β†’6 (decreasing then increasing). Day 3: Security goes 3β†’3β†’3β†’3β†’5β†’6 (non-increasing then non-decreasing). Both satisfy the 2-day time window requirement.
example_2.py β€” No Valid Days
$ Input: security = [1,1,1,1,1], time = 0
β€Ί Output: [0, 1, 2, 3, 4]
πŸ’‘ Note: With time=0, we only need to check the day itself. Since all days have equal security (satisfying both non-increasing and non-decreasing with length 0), all days are valid.
example_3.py β€” Insufficient Length
$ Input: security = [1,2,3,4,5,6], time = 2
β€Ί Output: []
πŸ’‘ Note: The array is strictly increasing, so no day has a non-increasing period before it (except the edges, but they don't have enough buffer days). No valid robbery days exist.

Constraints

  • 1 ≀ security.length ≀ 105
  • 0 ≀ security[i], time ≀ 105
  • The array represents guard counts per day
  • Days are 0-indexed

Visualization

Tap to expand
🏦 Bank Robbery Timing StrategyGood Day!Good Day!DecreasingIncreasingDay 0Day 5Day 10Day 15Valid robbery daySecurity levelLook for valleys withstable approach/exitOptimal Strategy: Pre-map all slopes, then find intersections - O(n) time!
Understanding the Visualization
1
Map the Terrain
Security levels form peaks and valleys over time
2
Find Downward Slopes
Count consecutive decreasing security days
3
Find Upward Slopes
Count consecutive increasing security days
4
Identify Valley Floors
Days where both slopes meet the time requirement
Key Takeaway
🎯 Key Insight: Instead of checking each day's neighborhood repeatedly, build a map of all slope directions first, then quickly identify where stable valleys occur!
Asked in
Google 45 Microsoft 38 Amazon 32 Meta 28
48.0K Views
Medium Frequency
~18 min Avg. Time
2.2K 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