Leetcode #683: K Empty Slots
In this guide, we solve Leetcode #683 K Empty Slots in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
You have n bulbs in a row numbered from 1 to n. Initially, all the bulbs are turned off.
Quick Facts
- Difficulty: Hard
- Premium: Yes
- Tags: Binary Indexed Tree, Segment Tree, Queue, Array, Ordered Set, Sliding Window, Monotonic Queue, Heap (Priority Queue)
Intuition
We are looking for a contiguous region that satisfies a constraint, which is a classic sliding-window signal.
Expanding and shrinking the window lets us maintain validity without restarting the scan.
Approach
Grow the window with a right pointer, and shrink from the left only when the constraint is violated.
Track the best window as you go to keep the solution linear.
Steps:
- Expand the right end of the window.
- While invalid, move the left end to restore constraints.
- Update the best window found.
Example
Input: bulbs = [1,3,2], k = 1
Output: 2
Explanation:
On the first day: bulbs[0] = 1, first bulb is turned on: [1,0,0]
On the second day: bulbs[1] = 3, third bulb is turned on: [1,0,1]
On the third day: bulbs[2] = 2, second bulb is turned on: [1,1,1]
We return 2 because on the second day, there were two on bulbs with one off bulb between them.
Python Solution
class BinaryIndexedTree:
def __init__(self, n):
self.n = n
self.c = [0] * (n + 1)
def update(self, x, delta):
while x <= self.n:
self.c[x] += delta
x += x & -x
def query(self, x):
s = 0
while x:
s += self.c[x]
x -= x & -x
return s
class Solution:
def kEmptySlots(self, bulbs: List[int], k: int) -> int:
n = len(bulbs)
tree = BinaryIndexedTree(n)
vis = [False] * (n + 1)
for i, x in enumerate(bulbs, 1):
tree.update(x, 1)
vis[x] = True
y = x - k - 1
if y > 0 and vis[y] and tree.query(x - 1) - tree.query(y) == 0:
return i
y = x + k + 1
if y <= n and vis[y] and tree.query(y - 1) - tree.query(x) == 0:
return i
return -1
Complexity
The time complexity is and the space complexity is , where is the number of bulbs. The space complexity is , where is the number of bulbs.
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.