O(n) single pass traverse flowerbed java solution


  • 0
    W

    public boolean canPlaceFlowers(int[] flowerbed, int n) {

        if(flowerbed.length==0) return false;
        int i = 0;
        
        while(n>0 && i<flowerbed.length){
            
            //try place first flower on flowerbed[0]
            if(i==0 && flowerbed[0]==0 && (flowerbed.length==1 || flowerbed[1]==0)){
                flowerbed[i] = 1;
                i+=2;
                n--;
            }
            
            //if previous plot, this plot and next plot is empty, plant flower 
            //take care of no left / right plots
            else if (i>0 && flowerbed[i-1]==0 && flowerbed[i]==0 && (i==flowerbed.length-1 || flowerbed[i+1]==0)){
                flowerbed[i] = 1;
                i+=2;
                n--;
            }
            
            else i++;
        }
        
        if(n>0) return false; //if there are flowers left
        else return true;
    }

Log in to reply
 

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