LeetCode 2020 Dec 5 Can Place Flowers

Problem: We have to check whether the given number of flowers can be placed in the flowser bed. The flowers can be placed when the value in the array is 0; and also it cannot be placed next to another flower.

The question is Leetcode

Inputs

n = Number of flowers to be place flowerBed [] = it is an integer array with values 0,1

Pseudo Code

  • We have check whether the flowerbed array (flowerbed) is null or not.
  • We need a variable to store the numberOfTreesPlace can be placed (this is optional). We can also decrement from the input itself (numberOfFlowerToPlace)
  • We have to iterate from first index till last.
  • At one time we are going to take 2 flowerbeds, current and the next index.
  • First we have to check whether current FlowerBed has flower and next index doesn't have flower (input can be given wrong, so its better to check) then we have to skip two index.
  • In case current index flower bed doesn't have flower and also the next index dont have flower; then we can place one flower in the current index and skip by two index.
  • Finally we can move to next index.
  • We continue till the end of final index.
  • Finally step outside of for loop is to check number of flowers placed vs number of flowers requested to place. If Number of flowers place is higher than number of flowers requested then we can return true, we can use ternary operator here.

Java Code

public boolean canPlaceFlowers(int[] flowerbed, int numberOfFlowerToPlace) {
       if(numberOfFlowerToPlace<0 || flowerbed ==null || flowerbed.length<=0){
                         return false;
                 } // end of null check

                 int numberOfTreesPlace = 0;

                 for(int indexATFlowerBed =0 ; indexATFlowerBed < flowerbed.length;){

                         int firstBed = flowerbed[indexATFlowerBed];
                         int secondBed = (indexATFlowerBed+1) <flowerbed.length ? flowerbed[indexATFlowerBed+1]: 0;

                         if( (firstBed==1 && secondBed==0)){
                                indexATFlowerBed = indexATFlowerBed+2;
                         }else if(firstBed==0 && secondBed==0){
                                 indexATFlowerBed = indexATFlowerBed+2;
                                 numberOfTreesPlace = numberOfTreesPlace+1;
                         }else{
                                 indexATFlowerBed = indexATFlowerBed+1;
                         }
                 }



                 return (numberOfTreesPlace >= numberOfFlowerToPlace);
    }