Java solution without modifying input array. 0(n) and 0(1) space


  • 0
    K

    compare if elem is zero and if (left index = -1 or left = 0) and (right index >= bed.length or right = 0) .

    public boolean canPlaceFlowers(int[] flowerbed, int n) {
            int count = 0, i = 0;
            while (i < flowerbed.length) {
                if (flowerbed[i] == 0 
                  && ((i - 1 == -1 || flowerbed[i - 1] == 0) 
                  && (i + 1 >= flowerbed.length || flowerbed[i + 1] == 0))) {
                    count ++;
                    //increment by two to avoid overlap
                    i += 2;
                } 
                else i++;
            }
            return count >= n;
        }
    

    O(n) time and O(1) space


Log in to reply
 

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