codeintuition-logo

Understanding the next closest occurrence pattern


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

Loading Image

Finding the next 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.