Monotonic Stack Implementation in TypeScript
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
Monotonic Stack in TypeScript: what you actually reach for
TypeScript implementation
/**
* 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 FreeThe TypeScript-specific trap
Performance in TypeScript, beyond the O(n)
Real-World Applications
Interview Tips & Practice
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).
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 trialBefore paying full price for a tool, check the student deals on AI and developer tools listed on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
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.