codeintuition-logo

Understanding the previous closest occurrence pattern


Some problems require us to find, for each item in a sequence, the previous closest occurrence of a greater or smaller item. One way to solve this problem would be to use nested loops to traverse backward from each item in the sequence until the required greater or smaller item is found. Consider the example below, where we must find the previous greater item for each item in the array.

Loading Image

Finding the previous greater item for all items in a sequence.

Even though the solution is correct, it requires expensive nested loops that makes the overall performance poor. We can leverage the LIFO (Last in, first out) property of a stack to solve this problem in a single pass without any nested loops using the closest occurrence technique.

Liking the course? Check our discounted plans to continue learning.