Windows, stacks and binary search
Patterns for sequences: sliding windows over contiguous parts, stacks and queues for nesting and next-greater problems, and binary search on lists and on answers.
About 5 hours of study
Learning objectives
- Slide a fixed or variable window in O(n)
- Match brackets and find next-greater values with a stack
- Binary search a rotated list and the answer of an optimisation problem
Lessons
- 1
Sliding windows
A window over a list or string that slides instead of restarting: fixed-size windows, the longest substring without repeats, and the smallest window that meets a condition.
- 2
Stacks and queues
Stacks for matching brackets and for monotonic-stack problems like the next greater element; queues and deques for breadth-first order and sliding-window maximums.
- 3
Binary search patterns
Binary search beyond "find x": the first position that passes a test, searching a rotated list, and binary search on the answer itself.
Module practice
- Best k days in a rowEasy
- Longest substring without repeatsMedium
- Shortest subarray with a big enough sumHard
- Balanced bracketsEasy
- Days until warmerMedium
- Largest rectangle in a histogramHard
- Where does it go?Easy
- Search a rotated listMedium
- Ship within D daysHard