739. Daily Temperatures

In the realm of algorithmic problem-solving, certain patterns and techniques emerge as powerful tools for tackling a variety of challenges. One such technique involves the clever use of stacks to efficiently solve problems that require finding the next greater element or value in an array. In this blog, we’ll explore how to leverage the stack data structure to solve the “Next Greater Element” problem in Java, using a practical example and step-by-step explanation.

Understanding the Problem: The “Next Greater Element” problem involves finding, for each element in an array, the first element to its right that is greater than the current element. This problem frequently arises in scenarios where you need to determine, for example, the next higher temperature in a weather forecast array or the next larger number in a sequence of integers.

Solution Approach: To solve the “Next Greater Element” problem efficiently, we can utilize a stack data structure to track elements as we traverse the array from right to left. Here’s how the solution works:

  1. We iterate through the input array in reverse order, starting from the last element.
  2. For each element encountered, we compare it with the elements currently in the stack.
  3. If the current element is greater than the top element of the stack, we pop elements from the stack until we find an element that is greater than the current element or until the stack is empty.
  4. If the stack becomes empty, it indicates that there is no greater element to the right of the current element.
  5. Otherwise, the top element of the stack is the next greater element, and we calculate its distance from the current element.
  6. We push the current element onto the stack to continue the comparison process.
  7. We repeat this process for all elements in the array, resulting in an array of distances representing the next greater element for each element in the input array.
class Pair {
    int value, index;
    Pair(int v, int i) {
        value = v;
        index = i;
    }
}

class Solution {
    public int[] dailyTemperatures(int[] temperatures) {
        Stack<Pair> stack = new Stack<>();
        int[] answer = new int[temperatures.length];
        
        for (int i = temperatures.length - 1; i >= 0; i--) {
            int element = temperatures[i];
            
            while (!stack.isEmpty() && stack.peek().value <= element) {
                stack.pop();
            }
            
            answer[i] = stack.isEmpty() ? 0 : stack.peek().index - i;
            stack.push(new Pair(element, i));
        }
        
        return answer;
    }
}

https://leetcode.com/problems/daily-temperatures/description/

Related Post