Question bankPricingSign in

Daily Temperatures

Stacks & QueuesMedium1:30

Given an array of daily temperatures, explain how you would find, for each day, how many days you would have to wait until a warmer temperature. If there is no future warmer day, the answer for that day is 0.

For example:

Input:  [73, 74, 75, 71, 69, 72, 76, 73]
Output: [1,  1,  4,  2,  1,  1,  0,  0]

Explanation: For day 0 (73 degrees), the next warmer day is day 1 (74 degrees), so the wait is 1 day. For day 2 (75 degrees), the next warmer day is day 6 (76 degrees), so the wait is 4 days.

How would you solve this more efficiently than checking every future day for each element?

Explain your approach and analyze the time and space complexity.

How to approach it

  • Hint 1

    A brute force approach checks all future days for each day, giving O(n^2). Think about how a stack could help.

  • Hint 2

    Consider iterating through the array and using a stack to keep track of indices of days whose warmer day has not been found yet.

  • Hint 3

    The stack should maintain a monotonically decreasing sequence of temperatures. When you encounter a warmer temperature, pop from the stack and calculate the difference in indices.

Ready to answer it out loud?

Record your answer in 1:30 and Preptile scores it 1–10 with specifics — what landed, what you skipped, and what to say next time.

Practising needs an invite code. Join the waitlist and we’ll send you one.