MCPcopy Create free account
hub / github.com/ashishps1/awesome-leetcode-resources / MonotonicStack

Class MonotonicStack

patterns/java/MonotonicStack.java:6–43  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

4import java.util.Stack;
5
6public class MonotonicStack {
7
8 public int[] nextGreaterElement(int[] nums) {
9 int n = nums.length;
10 int[] result = new int[n]; // Output array
11 Arrays.fill(result, -1); // Default to -1 if no greater element exists
12 Stack<Integer> stack = new Stack<>(); // Stack stores indices
13
14 // Iterate through the array
15 for (int i = 0; i < n; i++) {
16 // While stack is not empty and current element is greater than stack top
17 while (!stack.isEmpty() && nums[i] > nums[stack.peek()]) {
18 int index = stack.pop(); // Pop the top element
19 result[index] = nums[i]; // The current element is the Next Greater Element
20 }
21 stack.push(i); // Push the current index onto the stack
22 }
23 return result;
24 }
25
26 public int[] dailyTemperatures(int[] temperatures) {
27 int n = temperatures.length;
28 int[] result = new int[n]; // Result array initialized with 0s
29 Stack<Integer> stack = new Stack<>(); // Monotonic decreasing stack (stores indices)
30
31 // Iterate through the temperature array
32 for (int i = 0; i < n; i++) {
33 // While stack is not empty AND the current temperature is warmer than the temperature at stack top
34 while (!stack.isEmpty() && temperatures[i] > temperatures[stack.peek()]) {
35 int prevIndex = stack.pop(); // Pop the previous day's index
36 result[prevIndex] = i - prevIndex; // Calculate the wait time
37 }
38 stack.push(i); // Push current index onto the stack
39 }
40
41 return result; // Return the computed results
42 }
43}

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected