01The next greater element
Given an array, find for every element the first larger element to its right, or -1 if there is none. For 4 7 3 5 2 6 8 1 the answers are 7 8 5 6 6 8 -1 -1.
The obvious solution scans right from every position until it finds something bigger. On a decreasing array every scan runs to the end, so that is O(n²).
Notice what the slow scan wastes. When we look at 5, the earlier 3 is still waiting for its answer, and 5 is it. Any element is the answer for all the smaller waiting elements just before it. So keep the waiting elements somewhere and let each new value settle as many of them as it can.