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.
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
arr1andarr2such thatarr2is a subset ofarr1and all items inarr1are unique, for each item inarr2find the previous closest greater item inarr1. If an item does not have a previous greater value, use -1 for it.
Liking the course? Check our discounted plans to continue learning.