Poisonous Plants

Hard Monotonic Stack Monotonic Stack

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^5
  • 0 <= 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.

00:00
Testcase

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.

ApproachTimeSpace
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)

TimeO(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²).
SpaceO(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.

  1. Copy p into a list cur, and set days = 0.
  2. 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.
  3. If next has the same size as cur, no plant died: return days.
  4. 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++;
        }
    }
}

2Better (linked list, recheck only next to deaths)

TimeO(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.
SpaceO(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.

  1. Set prev[i] = i - 1 and next[i] = i + 1 for every plant.
  2. dying = every i with p[i] > p[i - 1]. These are the victims of day one.
  3. 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.
  4. 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.
  5. 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;
    }
}

3Optimal (monotonic stack of death days)

TimeO(n)Each index is pushed once and popped at most once, so the inner loop does O(n) work in total.
SpaceO(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).

  1. day[i] will hold the day plant i dies, with 0 meaning it never dies. Start with an empty stack and answer = 0.
  2. 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]).
  3. 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.
  4. Update answer = max(answer, day[i]) and push i.
  5. 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;
    }
}

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.