Two Pointers Pattern πŸ‘‰πŸ€―πŸ‘ˆ

Two Pointers Pattern πŸ‘‰πŸ€―πŸ‘ˆ

Two pointers is a common interview pattern often used to solve certain problems involving an iterable data structure, such as an array. As the name suggests, this technique uses two (or more) pointers that traverses through the structure. It does not have to be physically using two pointers. As long as the other pointer can be easily calculated from existing values, such as the index of the other pointer, it counts as a two pointer question.

Since two pointers is kind of a broad topic, there is no singular way to implement it. Depending on the questions you encounter, you need to implement the answer differently. Generally speaking, a two pointer algorithm has these characteristics:

  1. Two moving pointers, regardless of directions, moving dependently or independently
  2. A function that utilizes the entries referenced by the two pointers, which relates to the answer in a way
  3. An easy way of deciding which pointer to move
  4. A way to process the array when the pointers are moved

There are a lot of ways to classify two pointer problems. Below are some classifications, although they are in no way exhaustive.

Some classifications of two pointer problems include: two moving pointers, dependent or independent movements, functions utilizing entries referenced by pointers, easy decision-making on which pointer to move, and processing arrays when pointers move.