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 thatagoes first. - Ask whether you may change the input.
sort()andpush()change the caller’s array, andtoSorted()copies only the outer array, so build new ranges when you merge. - When you pop from an empty stack, JavaScript hands you
undefinedinstead of an error. Decide what an unmatched closing item means, and check for it.