Skip to content

Instantly share code, notes, and snippets.

@elishaking
Created February 20, 2020 19:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save elishaking/7c6d4c7597d9c5713f38d17a97508519 to your computer and use it in GitHub Desktop.
Save elishaking/7c6d4c7597d9c5713f38d17a97508519 to your computer and use it in GitHub Desktop.
Prefix Sums

Prefix Sums

Prefix sums is a tehnique that allows for the calculation of the sums M slices of a given array in constant time - O(1)

Given an array of length N, it's prefix sums can be calculated in linear time - O(N) like this

function prefixSums(A) {
  const sums = new Array(A.length + 1).fill(0);

  for (let i = 1; i < sums.length; i++) {
    sums[i] = sums[i - 1] + A[i - 1];
  }

  return sums;
}

Now using the prefix sums, we can calculate the total of any slice of array, A with length N in O(1)

/**
 * P ==> Prefix sums
 * X ==> start index of array slice - 0 <= X < Y
 * Y ==> end index of array slice - X < Y <= N
 */
function sliceTotal(P, X, Y) {
  return P[Y + 1] - P[X];
}

If we had M slices, the total time complexity will be O(M+N). Doing this using a regular for loop to calculate is slice-sum will produce a time complexity of O(M*N)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment