You have a long flowerbed in which some of the plots are planted, and some are not. However, flowers cannot be planted in adjacent plots.
Given an integer array
Output: true
Explanation: 1 flower can be placed at index 2.
Output: false
Explanation: 1 flower can be placed at index 2, but there is no spot for 2nd flower, so the answer is
Contents
Solution using one pass iteration through elements and check left and right side elements
In this approach, we are going to iterate through elements of input array
Special handling for left most element and right most elements:
-
If we are at index
0 , then there is nothing to check on left side, so we just check whether right side element is0 . -
If we are at index
flowebed.length -1 , there there is nothing to check on right side, so we just check whether left side element is0 .
Complexity Analysis:
Time complexity: Above code runs in O(n) time where
Space complexity: O(1).
Above implementations source code can be found at