Question Bank
/

JavaScript Binary Array Plant Pots: Two Approaches Quiz

JavaScript Binary Array Plant Pots: Two Approaches Quiz

Decide whether N new plants can be potted into a binary array of pots with no two plants adjacent. Two approaches (greedy single pass, lookahead with neighbour check), plus capacity counting and input validation.

Question Bank
Hard
JavaScript
quiz
arrays
greedy
interview-prep

350 views

8

Implement canPotted(input, N) using a single-pass GREEDY scan. Iterate left to right; whenever the current slot is 0 and both neighbours are 0 (or it is the first/last slot with the adjacent neighbour 0), plant a 1 and increment a counter. Return whether the counter reaches exactly N. The input must contain only 0 and 1; otherwise return false.

Examples

Example 1:

Input: [0, 0, 0, 0], N = 2
Output: true
Explanation: Plant at index 0 (neighbour right is 0), then index 2 (neighbours are 0). Result: [1,0,1,0]. 2 new plants matches N.

Example 2:

Input: [0, 1, 0], N = 2
Output: false
Explanation: No empty pot can be turned into a plant without sitting next to the existing 1.

3 more questions, with full solutions and explanations, are available for premium members.

Upgrade to Premium