codeintuition-logo

Identifying the comparator pattern


The custom compare technique can be used to solve some specific types of problems. There are generally medium or hard problems where we need to find the aggregated value of a function over the top k items in a dataset, where each item is of a user-defined type. Most problems solved using this technique require transforming a dataset where items are of primitive types to a dataset of items of a user-defined type. The transformation logic is often defined in the problem or is part of the solution. We also create a comparator to order data items in the heap that is used to find the top k items. 

If the problem statement or its solution follows the generic template below, it can be solved by applying the k-largest-items finding technique.

Template:

Transform the given dataset into one with user defined types and find the aggregated value of a function f over the top k items in the transformed dataset.

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