10 Common Heuristic - rFronteddu/general_wiki GitHub Wiki
First Heuristic
If the given input is sorted (array, list, or matrix), we will use a variation of Binary Search or a Two Pointers strategy.
K closest points to the origin:
Given an array of points in a 2D plane, find K closest points to the origin.
Example: Input: points = [1,2],[1,3](/rFronteddu/general_wiki/wiki/1,2],[1,3), K = 1, Output: [1,2](/rFronteddu/general_wiki/wiki/1,2)
Solution The Euclidean distance of a point P(x,y) from the origin can be calculated through the following formula: sqrt (x squared + y squared)
- We can use a Max Heap to find K points closest to the origin.
- We can start by pushing K points in the heap.
- While iterating through the remaining points:
- if a point (say P) is closer to the origin than the top point of the max-heap:
- we will remove that top point from the heap and add P to always keep the closest points in the heap.
- if a point (say P) is closer to the origin than the top point of the max-heap:
Second Heuristic
If we’re dealing with top/maximum/minimum/closest k elements among n elements, we will use a Heap.