Skip to the solution
MediumDSA6 min read

How do you find the next greater element for every item (Daily Temperatures)?

885 views

The problem

Question presented to candidate: "Given a list of daily temperatures, return a list where each entry says how many days you have to wait after that day for a strictly warmer temperature, or 0 if there is none. Please code it in Python and get it under O(n squared)."

What a strong answer should cover:

  • The O(nยฒ) brute force first, then the monotonic decreasing stack of indices that answers each day when a warmer day pops it.
  • Why it is O(n): each index is pushed once and popped at most once.
  • Strict < for strictly warmer, and the default 0 for days never popped.
  • The variants: circular (loop 2n with i % n) and the subset version with a hash map.
  • Python specifics: enumerate, [0] * n, a list as the stack with stack[-1], while stack and ..., and dict.get(x, -1) for the subset variant.

Clarifying questions expected:

  • "Is warmer strictly greater, or does an equal temperature count?"
  • "What should the answer be when no warmer day exists?"

Code / implementation expected: Yes โ€” a Python function using a list of indices as a monotonic stack.

  • dsa
  • monotonic-stack
  • arrays

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

6 min read ยท 11 sections

Python code

Edit the code and run it here. Each printed line with an expected value becomes a test.

PythonDaily Temperatures on the sample and edge cases
PythonBrute force vs monotonic stack: counting comparisons
PythonCircular next greater (LeetCode 503) and the hash-map subset (LeetCode 496)

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 58 of 154 in DSA

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All DSA questions
Up nextMedium

How do you rotate an array by k positions?

Continue