Identifying the previous closest occurrence pattern


The previous closest occurrence technique can only solve some specific problems. These are generally medium or hard problems involving linear data structures like arrays, strings, or linked lists where we need to find the previous greater or smaller item in the sequence. Most problems under this pattern can be solved by directly applying the previous closest occurrence technique, while some may require additional steps.

If the problem statement or its solution follows the generic template below, it can be solved by applying the previous closest occurrence technique.

Template:

Given a sequential data structure, find the previous closest greater or smaller item in the sequence.

Example

Let's consider the following problem as an example to better understand how to identify and solve a problem using the previous closest occurrence technique.

Problem statement: Given two arrays `arr1` and `arr2` such that `arr2` is a subset of `arr1` and all items in `arr1` are unique, for each item in `arr2` find the previous closest greater item in `arr1`. If an item does not have a previous greater value, use -1 for it.

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