Bitpath

Lesson 1 · Unit 03

Running totals

Any range sum in O(1) after one pass

12 exercisesabout 3 min

What you practise

  • Range sums in O(1)
  • The leading zero

Try a question from this lesson

Pick one

A shop logs daily sales: [4, 2, 7, 1, 5]. You will be asked for the total of days i to j thousands of times. What is worth computing once, up front?

The idea

Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.

Concept

Prefix sums

prefix[i] is the sum of the first i items, so prefix[0] is 0 and there are n + 1 entries.

The sum of the items from index i up to, but not including, j is prefix[j] - prefix[i]. Build once in O(n), then answer any range in O(1).

def build(nums):
    prefix = [0]
    for x in nums:
        prefix.append(prefix[-1] + x)
    return prefix

def range_sum(prefix, i, j):
    return prefix[j] - prefix[i]
function build(nums) {
  const prefix = [0];
  for (let i = 0; i < nums.length; i++) {
    prefix.push(prefix[i] + nums[i]);
  }
  return prefix;
}

function rangeSum(prefix, i, j) {
  return prefix[j] - prefix[i];
}
function build(nums: number[]): number[] {
  const prefix = [0];
  for (let i = 0; i < nums.length; i++) {
    prefix.push(prefix[i] + nums[i]);
  }
  return prefix;
}

function rangeSum(
  prefix: number[],
  i: number,
  j: number,
): number {
  return prefix[j] - prefix[i];
}

Python noteprefix[-1] is the last entry so far. Negative indexes count from the end of a list.

JavaScript noteWhen item i is added, the array has exactly i + 1 entries, so prefix[i] is its last one. prefix.at(-1) would also work.

TypeScript noteprefix.at(-1) has type number | undefined (the array might be empty), so it cannot be added without a check. prefix[i] is typed as plain number.

10 more exercises in the app

  • 2× type the answer
  • 3× multiple choice
  • 2× fill the blanks
  • 1× true or false
  • 1× order the lines
  • 1× match the pairs

Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.

One email when Bitpath is ready to try. Nothing else. Privacy