Categories
interview

K Empty Slots – Java

Time O(nlogn)
Space O(n)

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