Poisonous Plants
Poisonous Plants is a hard monotonic stack problem solved with the monotonic stack pattern.
The best approach, optimal (monotonic stack of death days), runs in O(n) time and O(n) space.
Below are 3 approaches in Java, Python, C++ and JavaScript, from brute force (simulate every day) up.
Problem
A row of n plants has been sprayed with pesticide, and p[i] is the amount on plant i, counted from the left.
Every day, each plant that holds strictly more pesticide than the plant directly to its left dies. All deaths of a day happen at the same moment, so the comparisons for that day are made on the row as it stood in the morning. After the dead plants are removed, the survivors close up, and a plant may get a new left neighbour for the next day. The leftmost plant never dies, since nothing is to its left.
Return the number of days after which no more plants die. If no plant ever dies, return 0.
Examples
Example 1
- Input
p = [3,6,2,7,5]- Output
2- Why
- On day one, 6 dies because 3 sits to its left, and 7 dies because 2 sits to its left. The 5 survives, since its left neighbour 7 is bigger. That leaves [3,2,5]. On day two, 5 now has 2 on its left, so it dies, leaving [3,2]. From then on nothing changes, so the answer is 2.
Example 2
- Input
p = [1,5,4,3,2]- Output
4- Why
- Each day only the plant right after the 1 is bigger than its left neighbour. So 5 dies on day one, 4 on day two, 3 on day three and 2 on day four. Only [1] is left.
Example 3
- Input
p = [4,3,3,1]- Output
0- Why
- No plant holds more pesticide than the plant to its left (an equal amount is not more), so no plant ever dies.
Constraints
1 <= p.length <= 10^50 <= p[i] <= 10^9
Solve it here
Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.
Your own testcases: Run checks these, and the expected output comes from our reference solution.
My submissions
Nothing yet. Every Run and Submit you make while signed in shows up here.
| When | Result | Tests | Runtime | Your time | Type |
|---|
Run checks the testcases above (3 examples, or your own). Submit also runs 16 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.
Animated walkthrough
A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
Solutions
Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.
| Approach | Time | Space |
|---|---|---|
| Brute force (simulate every day) | O(n · d) | O(n) |
| Better (linked list, recheck only next to deaths) | O(n) | O(n) |
| Optimal (monotonic stack of death days) | O(n) | O(n) |
1Brute force (simulate every day)
O(n · d)Each simulated day scans the whole remaining row, and there are d days, which can be close to n, so this can reach O(n²).O(n)The current row and the next row, each up to n values.Do exactly what the story says. Each day, build the next row from the current one: keep the first plant, and keep every other plant whose amount is at most the amount of its left neighbour in the current row. If nothing was removed, stop; otherwise count one more day.
- Copy p into a list cur, and set days = 0.
- Build next: add cur[0], then every cur[i] with cur[i] <= cur[i - 1], comparing inside cur, so all deaths of a day happen at once.
- If next has the same size as cur, no plant died: return days.
- Otherwise set cur = next, add one to days, and repeat.
class Solution {
public int poisonousPlants(int[] p) {
List<Integer> cur = new ArrayList<>();
for (int x : p) cur.add(x);
int days = 0;
while (true) {
List<Integer> next = new ArrayList<>();
next.add(cur.get(0));
for (int i = 1; i < cur.size(); i++) {
if (cur.get(i) <= cur.get(i - 1)) next.add(cur.get(i));
}
if (next.size() == cur.size()) return days;
cur = next;
days++;
}
}
}class Solution:
def poisonousPlants(self, p: List[int]) -> int:
cur = list(p)
days = 0
while True:
nxt = [cur[0]]
for i in range(1, len(cur)):
if cur[i] <= cur[i - 1]:
nxt.append(cur[i])
if len(nxt) == len(cur):
return days
cur = nxt
days += 1class Solution {
public:
int poisonousPlants(vector<int>& p) {
vector<int> cur(p.begin(), p.end());
int days = 0;
while (true) {
vector<int> next;
next.push_back(cur[0]);
for (int i = 1; i < (int)cur.size(); i++) {
if (cur[i] <= cur[i - 1]) next.push_back(cur[i]);
}
if (next.size() == cur.size()) return days;
cur = next;
days++;
}
}
};function poisonousPlants(p) {
let cur = p.slice();
let days = 0;
while (true) {
const next = [cur[0]];
for (let i = 1; i < cur.length; i++) {
if (cur[i] <= cur[i - 1]) next.push(cur[i]);
}
if (next.length === cur.length) return days;
cur = next;
days++;
}
}2Better (linked list, recheck only next to deaths)
O(n)Each plant is unlinked at most once, and each death adds at most one plant to recheck, so all days together do O(n) work.O(n)The prev, next and dead arrays, plus the lists of plants to check.Most of the row does not change from one day to the next. A survivor can only become a victim when its left neighbour changes, and that happens only when the plant to its left dies. So keep the living plants in a doubly linked list (prev and next arrays), find the victims of day one with one scan, and after each day only test the plant just to the right of each plant that died.
- Set prev[i] = i - 1 and next[i] = i + 1 for every plant.
- dying = every i with p[i] > p[i - 1]. These are the victims of day one.
- While dying is not empty: add one to days. For each victim j, mark it dead, unlink it (next[prev[j]] = next[j], prev[next[j]] = prev[j]) and remember r = next[j] as a plant to recheck.
- For each remembered r that is a real, living plant with a living left neighbour, it dies tomorrow when p[r] > p[prev[r]]. Those plants form the new dying list.
- When no plant is dying, return days.
class Solution {
public int poisonousPlants(int[] p) {
int n = p.length;
int[] prev = new int[n], next = new int[n];
boolean[] dead = new boolean[n];
for (int i = 0; i < n; i++) {
prev[i] = i - 1;
next[i] = i + 1;
}
List<Integer> dying = new ArrayList<>();
for (int i = 1; i < n; i++) if (p[i] > p[i - 1]) dying.add(i);
int days = 0;
while (!dying.isEmpty()) {
days++;
List<Integer> recheck = new ArrayList<>();
for (int j : dying) {
dead[j] = true;
if (prev[j] >= 0) next[prev[j]] = next[j];
if (next[j] < n) prev[next[j]] = prev[j];
recheck.add(next[j]);
}
List<Integer> tomorrow = new ArrayList<>();
for (int r : recheck) {
if (r < n && !dead[r] && prev[r] >= 0 && p[r] > p[prev[r]]) tomorrow.add(r);
}
dying = tomorrow;
}
return days;
}
}class Solution:
def poisonousPlants(self, p: List[int]) -> int:
n = len(p)
prev = [i - 1 for i in range(n)]
nxt = [i + 1 for i in range(n)]
dead = [False] * n
dying = [i for i in range(1, n) if p[i] > p[i - 1]]
days = 0
while dying:
days += 1
recheck = []
for j in dying:
dead[j] = True
if prev[j] >= 0:
nxt[prev[j]] = nxt[j]
if nxt[j] < n:
prev[nxt[j]] = prev[j]
recheck.append(nxt[j])
tomorrow = []
for r in recheck:
if r < n and not dead[r] and prev[r] >= 0 and p[r] > p[prev[r]]:
tomorrow.append(r)
dying = tomorrow
return daysclass Solution {
public:
int poisonousPlants(vector<int>& p) {
int n = p.size();
vector<int> prev(n), next(n);
vector<bool> dead(n, false);
for (int i = 0; i < n; i++) {
prev[i] = i - 1;
next[i] = i + 1;
}
vector<int> dying;
for (int i = 1; i < n; i++) if (p[i] > p[i - 1]) dying.push_back(i);
int days = 0;
while (!dying.empty()) {
days++;
vector<int> recheck;
for (int j : dying) {
dead[j] = true;
if (prev[j] >= 0) next[prev[j]] = next[j];
if (next[j] < n) prev[next[j]] = prev[j];
recheck.push_back(next[j]);
}
vector<int> tomorrow;
for (int r : recheck) {
if (r < n && !dead[r] && prev[r] >= 0 && p[r] > p[prev[r]]) tomorrow.push_back(r);
}
dying = tomorrow;
}
return days;
}
};function poisonousPlants(p) {
const n = p.length;
const prev = new Array(n), next = new Array(n);
const dead = new Array(n).fill(false);
for (let i = 0; i < n; i++) {
prev[i] = i - 1;
next[i] = i + 1;
}
let dying = [];
for (let i = 1; i < n; i++) if (p[i] > p[i - 1]) dying.push(i);
let days = 0;
while (dying.length > 0) {
days++;
const recheck = [];
for (const j of dying) {
dead[j] = true;
if (prev[j] >= 0) next[prev[j]] = next[j];
if (next[j] < n) prev[next[j]] = prev[j];
recheck.push(next[j]);
}
const tomorrow = [];
for (const r of recheck) {
if (r < n && !dead[r] && prev[r] >= 0 && p[r] > p[prev[r]]) tomorrow.push(r);
}
dying = tomorrow;
}
return days;
}3Optimal (monotonic stack of death days)
O(n)Each index is pushed once and popped at most once, so the inner loop does O(n) work in total.O(n)The day array and the stack, each up to n entries.Work out the day each plant dies instead of simulating. Plant i is finally killed by the nearest plant on its left with a smaller amount. Every plant between them has an amount at least p[i], and plant i cannot face its killer until all of them are gone. So plant i dies one day after the latest of those in-between plants, or on day one if there are none. Scan from left to right with a stack of indexes whose amounts strictly increase from bottom to top: popping the plants with amount at least p[i] visits exactly those in-between plants. If the stack runs empty, nothing smaller lies to the left, and plant i never dies (day 0).
- day[i] will hold the day plant i dies, with 0 meaning it never dies. Start with an empty stack and answer = 0.
- For each i from left to right, set worst = 0. While the top of the stack has p[top] >= p[i], pop it and set worst = max(worst, day[top]).
- If the stack is now empty, day[i] = 0. Otherwise the top is the nearest smaller plant on the left, and day[i] = worst + 1.
- Update answer = max(answer, day[i]) and push i.
- Return answer.
class Solution {
public int poisonousPlants(int[] p) {
int n = p.length;
int[] day = new int[n];
Deque<Integer> stack = new ArrayDeque<>();
int answer = 0;
for (int i = 0; i < n; i++) {
int worst = 0;
while (!stack.isEmpty() && p[stack.peek()] >= p[i]) {
worst = Math.max(worst, day[stack.pop()]);
}
day[i] = stack.isEmpty() ? 0 : worst + 1;
answer = Math.max(answer, day[i]);
stack.push(i);
}
return answer;
}
}class Solution:
def poisonousPlants(self, p: List[int]) -> int:
n = len(p)
day = [0] * n
stack = []
answer = 0
for i in range(n):
worst = 0
while stack and p[stack[-1]] >= p[i]:
worst = max(worst, day[stack.pop()])
day[i] = 0 if not stack else worst + 1
answer = max(answer, day[i])
stack.append(i)
return answerclass Solution {
public:
int poisonousPlants(vector<int>& p) {
int n = p.size();
vector<int> day(n, 0);
vector<int> stack;
int answer = 0;
for (int i = 0; i < n; i++) {
int worst = 0;
while (!stack.empty() && p[stack.back()] >= p[i]) {
worst = max(worst, day[stack.back()]);
stack.pop_back();
}
day[i] = stack.empty() ? 0 : worst + 1;
answer = max(answer, day[i]);
stack.push_back(i);
}
return answer;
}
};function poisonousPlants(p) {
const n = p.length;
const day = new Array(n).fill(0);
const stack = [];
let answer = 0;
for (let i = 0; i < n; i++) {
let worst = 0;
while (stack.length > 0 && p[stack[stack.length - 1]] >= p[i]) {
worst = Math.max(worst, day[stack.pop()]);
}
day[i] = stack.length === 0 ? 0 : worst + 1;
answer = Math.max(answer, day[i]);
stack.push(i);
}
return answer;
}Edge cases to test
- A single plant (answer 0)
- Values that never go up from left to right, including equal neighbours (answer 0)
- A strictly increasing row: everything except the first plant dies on day one (answer 1)
- A small value followed by a long falling run: one plant dies per day, so the answer is close to n
- A plant that survives day one but dies later, after its bigger left neighbour is gone
- Equal values: a plant with the same amount as its left neighbour does not die
Hints
Hint 1
Simulating the days works, but a falling run after a small value can take about n days, each costing O(n).
Hint 2
Only a plant whose left neighbour just died can start dying on a later day. Every other survivor already had a smaller or equal plant on its left.
Hint 3
Think about the day each plant dies. A plant i is killed by the nearest plant to its left with a smaller value. Before that, every plant in between with a value at least p[i] must already be gone.
Hint 4
Keep a stack of indexes whose values increase from bottom to top. When plant i pops plants with value at least p[i], it dies one day after the latest of them. If the stack empties, plant i never dies.
FAQ
What is the best time complexity for Poisonous Plants?
Optimal (monotonic stack of death days) runs in O(n) time and O(n) extra space. Each index is pushed once and popped at most once, so the inner loop does O(n) work in total.
Which pattern does Poisonous Plants use?
It is a monotonic stack problem that uses the monotonic stack pattern. Other problems with the same pattern: Next Greater Element I, Daily Temperatures, Next Greater Element II.
Is there a brute force solution for Poisonous Plants?
Yes. Brute force (simulate every day) takes O(n · d) time and O(n) space. Do exactly what the story says.
Which edge cases should I test for Poisonous Plants?
A single plant (answer 0); Values that never go up from left to right, including equal neighbours (answer 0); A strictly increasing row: everything except the first plant dies on day one (answer 1); A small value followed by a long falling run: one plant dies per day, so the answer is close to n; A plant that survives day one but dies later, after its bigger left neighbour is gone; Equal values: a plant with the same amount as its left neighbour does not die.