Skip to contentSaltar al contenido
125+ QA and SEO checks per page

Monotonic Stack Implementation in TypeScript

14 min readintermediate
Website QA and SEO audits

14-day free trial

Try SeekerPro free for 14 days.

Full access while you try it · then $15.99/mo · cancel anytime

Start your 14-day free SeekerPro trial →

30-day money-back guarantee · Cancel anytime

Not checking a site today? Turn this topic into a ready to paste AI prompt, free →

Key Takeaways

  • ✓Monotonic Stack runs in O(n) time and O(n) space, in TypeScript as in every other language.
  • ✓Array<number> at run time, identical to JavaScript. The contribution of the type system here is entirely about what happens at the boundary of the stack, where the compiler can be told that an index may be out of range.
  • ✓Turn on noUncheckedIndexedAccess and hoist the top into a local: const top = stack[stack.length - 1]; if (top === undefined) break.
  • ✓The TypeScript trap: Without noUncheckedIndexedAccess, TypeScript types every array index access as T rather than T | undefined, so stack[stack.length - 1] on an empty stack is typed number while being undefined at run time.
  • ✓All types are erased, so the generated JavaScript is byte-for-byte what you would have written by hand and the runtime characteristics are exactly those of the JavaScript version.

What Monotonic Stack actually is

A monotonic stack keeps its contents sorted in one direction by popping every element that would violate the order before pushing a new one. Because each element is pushed once and popped at most once, a loop that looks nested is linear overall, which is what turns next-greater-element, daily temperatures and largest-rectangle-in-a-histogram from quadratic scans into single passes. Almost every implementation stores indices rather than values, so that the distance between the current position and the position under the top of the stack gives you the span directly. The languages differ in what happens when you look at the top of an empty stack, and that single detail decides whether the guard is a truthiness test, an option match, a try-pattern or an exception.

Monotonic Stack in TypeScript: what you actually reach for

Array<number> at run time, identical to JavaScript. The contribution of the type system here is entirely about what happens at the boundary of the stack, where the compiler can be told that an index may be out of range.

TypeScript implementation

Turn on noUncheckedIndexedAccess and hoist the top into a local: const top = stack[stack.length - 1]; if (top === undefined) break. That converts the compiler complaint into a single explicit check instead of scattering non-null assertions across the loop condition.
typescript
/**
 * For each day, how many days until a warmer one. O(n) total.
 * Written to compile cleanly under noUncheckedIndexedAccess.
 */
export function dailyTemperatures(temps: readonly number[]): number[] {
  const answer: number[] = new Array<number>(temps.length).fill(0);
  const stack: number[] = [];

  for (let i = 0; i < temps.length; i++) {
    const current = temps[i]!;          // i < length, provably in range

    for (;;) {
      // Hoist once. Narrowing on stack[...] would be discarded by any
      // intervening call, and at(-1) is number | undefined by design.
      const top = stack.at(-1);
      if (top === undefined) break;
      if (temps[top]! >= current) break;

      stack.pop();
      answer[top] = i - top;
    }
    stack.push(i);
  }
  return answer;
}

/** Next greater element to the right, or -1. */
export function nextGreater(nums: readonly number[]): number[] {
  const out: number[] = new Array<number>(nums.length).fill(-1);
  const stack: number[] = [];
  for (let i = 0; i < nums.length; i++) {
    let top = stack.at(-1);
    while (top !== undefined && nums[top]! < nums[i]!) {
      out[top] = nums[i]!;
      stack.pop();
      top = stack.at(-1);
    }
    stack.push(i);
  }
  return out;
}

Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.

Paste your code. Click QA. Get an instant expert-level audit with fixes.

QA My Code Free

The TypeScript-specific trap

Without noUncheckedIndexedAccess, TypeScript types every array index access as T rather than T | undefined, so stack[stack.length - 1] on an empty stack is typed number while being undefined at run time. The compiler confidently hides the exact class of bug it exists to catch. With the flag on, the correct code is slightly more verbose and many developers reach for the non-null assertion, which restores the unsoundness by hand. Note that at(-1) is typed T | undefined regardless of the flag, which makes it the safer accessor.

Performance in TypeScript, beyond the O(n)

All types are erased, so the generated JavaScript is byte-for-byte what you would have written by hand and the runtime characteristics are exactly those of the JavaScript version. The asymptotic cost is the same in every language, O(n) time and O(n) space describe the algorithm, not the runtime, so these constant factors and allocation patterns are the part that actually differs when you port Monotonic Stack between languages.

Real-World Applications

Monotonic Stack applies wherever its problem shape appears in your own code. In TypeScript, check whether the standard library or a well maintained package already provides it before you write your own. Understanding Monotonic Stack helps you reason about the tools you use daily and make better architectural decisions in your own projects.

Interview Tips & Practice

Monotonic Stack appears frequently in onsite coding rounds at mid-to-large tech companies. When presenting your solution: (1) clarify the problem constraints before coding, (2) explain your approach verbally including why you chose Monotonic Stack over alternatives, (3) implement step by step with clean variable names, (4) analyze time and space complexity explicitly, and (5) discuss optimizations and trade-offs. Common follow-up questions include: Can you optimize the space complexity? How does this handle concurrent access? What if the input does not fit in memory? Practice variations of Monotonic Stack to build pattern recognition. In TypeScript, demonstrate proficiency with generics and type guards to show language mastery alongside algorithmic thinking. Companies value candidates who write idiomatic TypeScript code that is both correct and maintainable.

Frequently Asked Questions

Which TypeScript type or library should I use for Monotonic Stack?

Array<number> at run time, identical to JavaScript. The contribution of the type system here is entirely about what happens at the boundary of the stack, where the compiler can be told that an index may be out of range.

What is the most common TypeScript mistake when implementing Monotonic Stack?

Without noUncheckedIndexedAccess, TypeScript types every array index access as T rather than T | undefined, so stack[stack.length - 1] on an empty stack is typed number while being undefined at run time. The compiler confidently hides the exact class of bug it exists to catch. With the flag on, the correct code is slightly more verbose and many developers reach for the non-null assertion, which restores the unsoundness by hand. Note that at(-1) is typed T | undefined regardless of the flag, which makes it the safer accessor.

How does Monotonic Stack actually perform in TypeScript?

All types are erased, so the generated JavaScript is byte-for-byte what you would have written by hand and the runtime characteristics are exactly those of the JavaScript version. Time complexity is O(n) and space is O(n).

Share this article

🔥 Enjoyed this? Share with someone who'd love it

Related Articles

Rather try before you buy?

Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.

Start my 14-day SeekerPro trial

Before paying full price for a tool, check the student deals on AI and developer tools listed on Noizz.

Is YOUR site's SEO this optimized?

Find out in 60 seconds with a free QA audit.

Free SEO Check

Is your site built to last?

Run a free QA audit and get your Site Health Score in seconds.

Check Your Site Free

No signup required

Thousands of audits runAverage 23-point score improvement95% fix success rateAudit yours

How does your site compare?

Paste your URL below. Get a complete QA report with SEO score, accessibility issues, security checks, and a one-click fix prompt. Free. No signup.

Takes 30 seconds. No signup. Generates a fix-everything prompt.

Explore More Topics

Engagement

0

Reader comments

No account needed. Share what worked, what did not, and what you would add.

Add your take below. A concrete tip, a result or a question helps the next reader most.