K Empty Slots

First day on which two bloomed flowers are exactly k slots apart with all between unbloomed — sliding-window min over a day-array.

Hard
Time O(n) Space O(n)
LeetCode
5 min read
top-k sliding-window monotonic-deque

Problem#

bulbs[i] is the slot that turns on day i+1 (1-indexed slot, distinct). Return the first day on which there exist two on-slots exactly k slots apart with all slots between them off — or -1.

Examples#

  • bulbs = [1,3,2], k = 12
  • bulbs = [1,2,3], k = 1-1

Hints#

Hint 1
Invert: days[slot] = day it blooms. The answer is the first window [i, i+k+1] where max(days[i+1..i+k]) < min(days[i], days[i+k+1]).

Approach#

Build days[i] = day slot i blooms. Slide a window of length k + 2: it’s valid iff the two endpoint days are both less than every interior day. Equivalently, the smaller endpoint day is the answer when interior all exceed it.

Solution#

K Empty Slots
class Solution {
public:
int kEmptySlots(vector<int>& bulbs, int k) {
int n = bulbs.size();
vector<int> days(n);
for (int i = 0; i < n; ++i) days[bulbs[i] - 1] = i + 1;
int ans = INT_MAX;
int l = 0, r = k + 1;
while (r < n) {
bool ok = true;
for (int i = l + 1; i < r; ++i) {
if (days[i] < days[l] || days[i] < days[r]) {
l = i; r = i + k + 1;
ok = false; break;
}
}
if (ok) {
ans = min(ans, max(days[l], days[r]));
l = r; r = r + k + 1;
}
}
return ans == INT_MAX ? -1 : ans;
}
};

Editorial#

The inversion slot → day is the key trick. With the inversion, the “k empty between two on” condition is a simple range-min vs endpoint comparison. The sliding-with-skip pattern (advance l to the first interior violation) keeps the algorithm linear amortized: each index is examined O(1) times.

Complexity#

  • Time: O(n) amortized.
  • Space: O(n).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.