LeetCode — Can Place Flowers

Sridhar Yalla
Dec 5, 2020

Problem Link : https://leetcode.com/problems/can-place-flowers/

Solution

Looking at the problem it is a good candidate for trying some greedy solution.

Basically we can place a flower at a[i] if it meets below three conditions.

  • a[i] == 0 ( i.e. current position is empty)
  • a[i-1] == 0 ( previous position is empty)
  • a[i+1 ==0 (next position is empty)

Also we need to mind the boundary condition of first and last positions as they don’t have previous and next elements respectively.

We can try placing placing N flowers satisficing above and stop the loop once we run out of flowers.

Below is the code snippet to solve the above

--

--