Sliding window
Many problems ask something about consecutive stretches of a list or string: the largest sum of 3 consecutive items, the longest…
A few ideas solve a huge number of problems. In this lesson you will learn the patterns that repeat the most: the sliding window, prefix sums, two pointers, greedy algorithms and working with intervals. You will see how to go from a slow solution, which looks at everything again and again, to one that walks through the data just once, and when a greedy strategy is correct and when it is not.
Many problems ask something about consecutive stretches of a list or string: the largest sum of 3 consecutive items, the longest…
If you are going to answer many sum queries over ranges of the same list, do not recompute each time: precompute the prefix sums…
The two pointers technique uses two indexes that move through the same structure, usually one from each end, to avoid a double…
A greedy algorithm builds the solution step by step, always choosing the best local option , without going back. It is very…
Interval problems (meetings, bookings, time ranges) are almost always solved with two ideas: sort by start and walk once, or turn…
A fixed-size sliding window of size k moves along the list: when it advances one element enters and another leaves, so the sum is…
With a variable-size window you extend it on the right and shrink it on the left when a repeated character appears. A dictionary…
If you store the prefix sums (the running sum up to each position), the sum of any range is obtained with a single subtraction…
With prefixes and a dictionary you can count in O(n) the consecutive ranges that add up to k : a range adds up to k if the…
With two pointers starting at the ends and moving towards the centre, each pair of characters is compared. Here only letters and…
Each number is the height of a wall. Two walls form a container of area distance × smaller height . With two pointers from the…
If you sort the intervals by their start, the overlapping ones end up next to each other and one pass is enough to merge them…
To know how many meetings overlap at once, you create events (start +1, end −1), sort them by time and keep count of the active…
A greedy algorithm picks the locally best option at each step. To fit the maximum number of activities without overlaps, the…
Each number is the maximum jump that can be made from that position. A greedy strategy keeps the farthest reachable position at…