Home Algorithm Templates
Post
Cancel

Algorithm Templates

Two Pointers / Sliding Window / Prefix Sums

  • https://tianjietalk.notion.site/03-6c5caefe2f61469c81befc5a8e4f7854

    Two Pointers

    Left and Right Pointers

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    
    public void template(int[] nums) {
      int left = 0;
      int right = nums.length - 1;
      while(left < right) {
          if () {
              left++;
          }
          if () {
              right++;
          }
      }
    }
    

Fast and Slow Pointers / Sliding Window

1
2
3
4
5
6
7
8
9
10
11
12
13
public void template(int[] nums) {
    int left = 0;
    int right = 1;
    while(right < nums.length) {
        if() {
            left++;
        }

        if() {
            right++;
        }
    }
}

Prefix Sums

  • Main idea: the consecutive totals of the first 0, 1, 2, …, n elements of an array.
  • Allow to calculate the total of any slice of the array very quickly
This post is licensed under CC BY 4.0 by the author.