LeetCode – K Empty Slots (Java)

Given a garden with N slots. In each slot, there is a flower. Each of the N flowers will bloom one by one in N days. In each day, there will be exactly one flower blooming and it will stay blooming since then.

Given an array of numbers from 1 to N. Each number in the array is the slot where the flower will open in (i+1)-th day. For example, the array [5, 3, 1, 4, 2] means flow 5 will bloom in day 1, flower 3 will bloom in day 2, flower 1 will bloom in day 3, etc.

Given an integer k, return the earliest day in which there exists two flowers blooming and also the flowers between them is k and these flowers are not blooming.

Java Solution 1

public int kEmptySlots(int[] flowers, int k) {
    int[] days = new int[flowers.length + 1];
    for (int i = 0; i < flowers.length; i++) {
        days[flowers[i]] = i + 1;
    }
 
    int result = Integer.MAX_VALUE;
 
    for (int i = 1; i < days.length - k - 1; i++) {
        int l = days[i];
        int r = days[i + k + 1];
 
        int max = Math.max(l, r);
        int min = Math.min(l, r);
 
 
        boolean flag = true;
        for (int j = 1; j <= k; j++) {
            if (days[i + j] < max) {
                flag = false;
                break;
            }
        }
 
        if (flag && max < result) {
            result = max;
        }
    }
 
    return result == Integer.MAX_VALUE ? -1 : result;
}

Time complexity is O(N*k) and space complexity is O(N).

Java Solution 2

public int kEmptySlots2(int[] flowers, int k) {
    TreeSet<Integer> set = new TreeSet<>();
 
    for (int i = 0; i < flowers.length; i++) {
        Integer higher = set.higher(flowers[i]);
        Integer lower = set.lower(flowers[i]);
 
        if (lower != null && flowers[i] - k - 1 == lower) {
            return i + 1;
        }
 
        if (higher != null && flowers[i] + k + 1 == higher) {
            return i + 1;
        }
 
        set.add(flowers[i]);
    }
 
    return -1;
}

Time complexity is O(N*log(N)) and space complexity is O(N).

Leave a Comment