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.

Example

Second Heuristic

If we’re dealing with top/maximum/minimum/closest k elements among n elements, we will use a Heap.

If we need to try all combinations (or permutations) of the input, we can either use recursive Backtracking or iterative Breadth-First Search.

Most of the questions related to Trees or Graphs can be solved either through Breadth First Search or Depth First Search

Every recursive solution can be converted to an iterative solution using a stack

For a problem involving arrays, if there exists a solution in O(n squared) time and O(1) space, there must exist two other solutions: 1) using a HashMap or a Set for (O(n) time and O(n) space, 2) using sorting for O(n log n) time and O(1) space.

If a problem is asking for optimization (max or min), we will be using dynamic programming

if we need to find some commons ubstring among a set of strings, we will be using a HashMap or a Trie

If we need to search/manipulate a bunch of strings, Trie will be the best data structure

If the problem is related to a LinkedList and we can't use extra space, then use the Fast&Slow Pointer approach.