Skip to content

Commit 08efc3c

Browse files
committed
Day 2 of leet code
1 parent a1136c3 commit 08efc3c

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
/**
2+
* https://leetcode.com/problems/can-place-flowers/editorial/?envType=study-plan-v2&id=leetcode-75
3+
* 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.
4+
5+
Given an integer array flowerbed containing 0's and 1's, where 0 means empty and 1 means not empty, and an integer n, return true if n new flowers can be planted in the flowerbed without violating the no-adjacent-flowers rule and false otherwise.
6+
*/
7+
8+
function canPlaceFlowers(flowerbed: number[], n: number): boolean {
9+
10+
// [1, 0, 0, 0, 1]
11+
// 1
12+
13+
// [1, 0, 0, 0, 1]
14+
// x x x
15+
16+
// plants more than the slots -> false
17+
18+
let prevState = 0;
19+
let nextState = 0;
20+
// O(N)
21+
for (let i = 0; i < flowerbed.length; i++) { // 0 1
22+
if (n === 0) break;
23+
// Plot empty check
24+
if (flowerbed[i]) continue; // return F
25+
// Start check
26+
if (i === 0) {
27+
// Check next state and place
28+
nextState = flowerbed[i + 1];
29+
}
30+
31+
// Normal Cases
32+
if (i > 0) prevState = flowerbed[i - 1]; // 1
33+
if (i < flowerbed.length - 1) nextState = flowerbed[i + 1]; // 0
34+
if (!(prevState || nextState)) { // false
35+
flowerbed[i] = 1;
36+
n -= 1;
37+
}
38+
}
39+
return n <= 0;
40+
};

0 commit comments

Comments
 (0)