easyStackPattern: Monotonic Stack

Daily Temperature Threshold Solution

Problem Statement

You are given an array of integers `temperatures` representing daily peak temperatures. For each day, determine the number of days until a day with a higher temperature arrives. If no such day exists, return -1.

Examples

Example 1:
Input:[73, 74, 75, 71, 69, 72, 76, 73]
Output:[1, 1, 4, 2, 1, 1, -1, -1]
Explanation: next greater element for each day
Example 2:
Input:[10, 20, 30, 40, 50]
Output:[1, 1, 1, 1, -1]
Explanation: increasing temperatures

Constraints

  • 1 <= n <= 10^5
  • 1 <= arr[i] <= 10^9
Time: O(N) Space: O(N)
Iterate from right to left. Use a stack. While stack not empty and top is <= current element, pop. If stack is empty, answer is -1. Else, answer is stack top. Push current element. Time O(N), Space O(N).

Run, Test & Submit Code

Ready to practice this challenge? Launch our interactive compilation environment with compiler validation.

Solve on Interactive Workspace

Tested Solutions

No solution code is currently loaded.
Complete this code in the workspace editor.