[C++]Easy Solution with Set

  • 0

    STL set is ordered, so we can make use of this property to find the difference between the newly inserted value with previous one and following one. If anyone of them satisfies condition k, then return the day.

    class Solution {
       int kEmptySlots(vector<int>& flowers, int k) {
           set<int> pos_set;
           for(int i=1; i<flowers.size(); i++){
               auto it = pos_set.insert(flowers[i]).first;
               if(it != pos_set.begin()){
                   if(*it - *prev(it)-1 == k){
                       return i+1;
               if(next(it) != pos_set.end()){
                   if(*next(it) - *it -1 == k){
                       return i+1;
           return -1;

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.