You have n bulbs in a row numbered from 1 to n. Initially, all the bulbs are turned off. We turn on exactly one bulb every day until all bulbs are on after n days.

You are given an array bulbs of length n where bulbs[i] = x means that on the (i+1)th day, we will turn on the bulb at position x where i is 0-indexed and x is 1-indexed.

Given an integer k, return the minimum day number such that there exists two turned on bulbs that have exactly k bulbs between them that are all turned off. If there isn't such day, return -1.

Input & Output

Example 1 — Basic Case
$ Input: bulbs = [1,3,2], k = 1
Output: 2
💡 Note: Day 1: bulb 1 is on. Day 2: bulb 3 is on, now we have bulbs 1 and 3 with exactly 1 bulb (position 2) between them that is off. Return day 2.
Example 2 — No Valid Pattern
$ Input: bulbs = [1,2,3], k = 1
Output: -1
💡 Note: Day 1: bulb 1 on. Day 2: bulbs 1,2 on (no gap). Day 3: bulbs 1,2,3 on (no valid k=1 gap). Return -1.
Example 3 — Larger Gap
$ Input: bulbs = [1,5,3], k = 2
Output: -1
💡 Note: Day 1: bulb 1 on. Day 2: bulb 5 on, bulbs 1 and 5 have 3 positions between them (not k=2). Day 3: bulb 3 on, but no two lit bulbs have exactly k=2 positions between them. Return -1.

Constraints

  • 1 ≤ bulbs.length ≤ 2 × 104
  • 1 ≤ bulbs[i] ≤ bulbs.length
  • bulbs is a permutation of numbers from 1 to bulbs.length
  • 0 ≤ k ≤ 2 × 104

Visualization

Tap to expand
K Empty Slots - Binary Indexed Tree Approach INPUT Bulb Positions (1-indexed) 1 2 3 bulbs array (turn-on order) [1, 3, 2] Day 1 Day 2 Day 3 k = 1 (empty slots between) k = 1 Find day when 2 ON bulbs have exactly k OFF between ALGORITHM STEPS 1 Build days array days[pos] = turn-on day 1 3 2 2 BIT for range queries Track ON bulbs count Fenwick Tree: O(log n) queries 3 Process each day Turn on bulb, update BIT Day 1: pos=1 ON Day 2: pos=3 ON [OK!] 4 Check k-gap condition Query: any ON in [pos-k-1, pos-1] or [pos+1, pos+k+1] pos 1 and 3: exactly 1 OFF between FINAL RESULT State at Day 2: ON OFF ON pos 1 pos 2 pos 3 k=1 Answer: 2 On Day 2, bulbs at positions 1 and 3 are ON with exactly 1 OFF bulb (position 2) between them Output: 2 Key Insight: Binary Indexed Tree (Fenwick Tree) enables O(log n) range sum queries to count ON bulbs in any interval. For each newly turned ON bulb at position p, we check if there's exactly one ON bulb at distance k+1 with all k positions between being OFF. Time Complexity: O(n log n), Space: O(n) TutorialsPoint - K Empty Slots | Binary Indexed Tree (Fenwick Tree) Approach
Asked in
Google 25 Facebook 18 Amazon 12 Microsoft 8
28.5K Views
Medium Frequency
~35 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