Clean java solution O(n)- No changes to input array


  • 0
    A
    public boolean canPlaceFlowers(int[] flowerbed, int n) {
        for(int i=0; i<flowerbed.length && n>0; i++) {
            if(flowerbed[i] == 0 && (i == 0 || flowerbed[i-1] == 0) && (i == flowerbed.length-1 || flowerbed[i+1] == 0)) {
                n--;
                i++;
            }
        }
        
        return n == 0;
    }
    
    Time complexity:  O(n)
    Space complexity: O(1)

Log in to reply
 

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