Locked learning resources

Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Locked learning resources

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Stacks, Queues, and Intervals (Summary)

You’ve practiced two patterns for problems where order decides the answer:

  • Stacks hold the work that’s still open, so the newest open item is always the next one to settle. Brackets, HTML tags, keystrokes, URL paths, and “the next higher price” all fit this shape. Each item is pushed and popped at most once, so the whole pass is O(n).
  • Queues serve items in arrival order, which makes them the natural fit for time windows like a rate limit. In JavaScript, read from a head index instead of calling shift(), which moves every remaining item.
  • Sorting and intervals turn an all-pairs comparison into one sweep. Sort by start to detect, merge, or intersect ranges, sort by end to keep as many as possible, and expect the O(n log n) sort to dominate the cost.

Things to Remember in an Interview

  • Settle the boundary before you code: does a meeting that ends at 10:00 clash with one that starts at 10:00? Then test exactly that case.
  • Give sort() a comparator that returns a number, such as (a, b) => a[0] - b[0]. Without one, numbers are compared as strings, and a boolean comparator never tells the engine that a goes first.
  • Ask whether you may change the input. sort() and push() change the caller’s array, and toSorted() copies only the outer array, so build new ranges when you merge.
  • When you pop from an empty stack, JavaScript hands you undefined instead of an error. Decide what an unmatched closing item means, and check for it.

Keep Practicing

Locked learning resources

Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Locked learning resources

The full lesson is for members only. Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Become a Member to join the conversation.