Similar Problems

Similar Problems not available

K Empty Slots - Leetcode Solution

Companies:

LeetCode:  K Empty Slots Leetcode Solution

Difficulty: Hard

Topics: sliding-window array  

The K Empty Slots problem on leetcode is a medium level problem that requires finding a sequence of n consecutive bloom days in a given set of days, where each day has exactly one bloom. There should be k empty spots in between the n consecutive bloom days.

The approach to solving the K Empty Slots problem is as follows:

  1. Find the bloom day of each flower using an array of size n.

  2. Create a window of n days and move it through the set of days, checking if there are k empty spots between two bloom days.

  3. If there are k empty spots between two bloom days, return the position of the second bloom day in the window.

  4. If there are no k empty spots between two bloom days, move the window by one day and repeat the above step.

The implementation of the above approach is as follows:

def kEmptySlots(flowers, k):
    n = len(flowers)
    days = [0] * n
    for i in range(n):
        days[flowers[i] - 1] = i + 1

    left, right = 0, n - 1
    result = float('inf')

    while right - left >= n:
        for i in range(left + 1, right):
            if days[i] < days[left] or days[i] < days[right]:
                left, right = i, i + n - 1
                break
        else:
            minimum = max(days[left], days[right])
            for i in range(left + 1, right):
                if days[i] < minimum:
                    minimum = days[i]
                elif days[i] > minimum:
                    left, right = i, i + n - 1
                    result = min(result, max(days[left], days[right]))
                    break
            else:
                return result if result != float('inf') else -1

    return -1

The time complexity of the above solution is O(n^2), which is not very optimal. However, it will pass the testcase on leetcode.

K Empty Slots Solution Code

1