Typorithm · medium

Daily Temperatures

daily-temperaturesstacks-queuesmonotonic-stacknext-greaterindices
Saved on this device
Full lesson · 8 learning steps Open any exercise for focused practice
1

Step 1 of 8 · intro card

Learn Daily Temperatures

0%

Stacks & Queues

Keep a stack of indices with decreasing temperatures; a warmer day resolves all cooler ones below it.

Each day needs the distance to the next warmer day, a next-greater-element problem.

A monotonic stack of indices holds days still waiting for something warmer.

When today is warmer, it pops and resolves every cooler day, recording the index gap.

01

Stack holds waiting indices.

02

Warmer day resolves cooler ones.

03

Answer is the index gap.

function dailyTemperatures(temps) {
  const result = new Array(temps.length).fill(0);
  const stack = [];

  for (let i = 0; i < temps.length; i += 1) {
    while (stack.length > 0 && temps[i] > temps[stack[stack.length - 1]]) {
      const prev = stack.pop();
      result[prev] = i - prev;
    }

    stack.push(i);
  }

  return result;
}

Read the implementation

Connect each part of the code to the concept before you type.

1. Index stack

The stack holds indices waiting for a warmer day.

const stack = []

2. Warmer found

Today resolves every cooler day still on the stack.

while (stack.length > 0 && temps[i] > temps[stack[stack.length - 1]])

3. Days waited

The gap in indices is the days until a warmer temperature.

result[prev] = i - prev

4. Wait for warmer

Today's index waits until a warmer day appears.

stack.push(i)

A complete learning loop

01

Understand

Read the concept map and follow the code breakdown.

02

Reconstruct

Type the implementation, repair mistakes and work through every recall exercise.

03

Verify

Use the final check without hints; revisit weak concepts in short practice sessions.

Daily Temperatures: Lesson & Practice · Typorithm | ApplyDjinn