K Empty Slots in C++


Suppose we have N bulbs in a row and they are numbered from 1 to N. At first, all the bulbs are off. We can turn on exactly one bulb everyday until all bulbs are on after N days. If we have an array bulbs of length N where bulbs[i] = x this indicates that on the (i+1)th day, we will turn on the bulb at position x. If we have another integer K, such that out the minimum day number such that there exists two turned on bulbs that have exactly K bulbs between them that are all off. If there is no such day, then return -1.

So, if the input is like bulbs: [1,3,2] and K = 1, then the output will be 2 as

  • On the first day: bulbs[0] = 1, the first bulb is turned on: [1,0,0]

  • On the second day: bulbs[1] = 3, then the third bulb is turned on: [1,0,1]

  • On the third day: bulbs[2] = 2, then the second bulb is turned on: [1,1,1]

We will return 2 because on the second day, there were two on bulbs with one off bulb between them.

To solve this, we will follow these steps −

  • n := size of bulbs

  • for initialize i := 0, when i < n, update (increase i by 1), do −

    • days[bulbs[i] - 1] = i + 1

  • left := 0, right := k + 1, ret := inf

  • for initialize i := 0, when right < n, update (increase i by 1), do −

    • if days[i] < days[left] or days[i] <= days[right], then −

      • if i is same as right, then −

        • ret := minimum of ret and maximum of days[left] and days[right]

      • left := i

      • right := i + k + 1

  • return (if ret is same as inf, then -1, otherwise ret)

Let us see the following implementation to get better understanding −

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
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 left = 0;
      int right = k + 1;
      int ret = INT_MAX;
      for (int i = 0; right < n; i++) {
         if (days[i] < days[left] || days[i] <= days[right]) {
            if (i == right) {
               ret = min(ret, max(days[left], days[right]));
            }
            left = i;
            right = i + k + 1;
         }
      }
      return ret == INT_MAX ? -1 : ret;
   }
};
main(){
   Solution ob;
   vector<int> v = {1,3,2};
   cout << (ob.kEmptySlots(v, 1));
}

Input

{1,3,2},

Output

2

Updated on: 11-Jul-2020

193 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements