![]() |
VOOZH | about |
Given an integer array plots[] containing 0s and 1s, where plots[i] = 0 means ith plot is empty and plots[i] = 1 means ith plot is planted with flower. The task is to check if N new flowers can be planted in empty plots such that no two flowers are adjacent.
Examples:
Input: plots[] = {1, 0, 0, 0, 1}, N = 1
Output: True
Explanation: You can plant flowers at positions 2 without violating the no-adjacent-flowers rule.Input: plots[] = {1, 0, 0, 0, 1}, N = 2
Output: False
Explanation: You cannot plant flowers 2 without violating the no-adjacent-flowers rule.
Approach: To solve the problem, follow the below idea:
The problem can be solved by iterating through the plots and check for empty plots where a new flower can be planted. For each empty plot, we check if the plot before and after it are also empty or out of bounds (if the plot is at the ends). We keep a count of how many flowers we can plant as we go through the plots. If the count reaches or exceeds N, we return true. If we finish iterating through the plots and the count is less than N, we return false.
Step-by-step algorithm:
Below is the implementation of the algorithm:
False
Time Complexity: O(M), where M is the length of the plots array
Auxiliary Space: O(1)