Hone

Lessons · TypeScript · scanning an array is slow

One pass, one running fact

Walk the array once and keep a single number about the past; that is often all you need.

Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.

What it is for

Streams of prices, events and readings cannot be re-read, and one pass over a million items is fine where a pass per item is not.

How to think about it

Ask: at each item, what one thing about earlier items decides the answer here? Keep that in a variable; use it, then update it.

Worked example

const prices = [5, 3, 8, 2, 9];
Best rise from an earlier price to a later one.
let low = prices[0], best = 0;
The running fact: the lowest so far.
for (const p of prices) {
Once through.
  best = Math.max(best, p - low);
Judge the present with the past...
  low = Math.min(low, p);
...then update the past.
}

Your turn

Find the largest number in one pass.

let biggest = nums[0];
for (const n of nums) if (n > )  = n;

The trap

Updating the running fact before using it on the current item.

Practise scanning an array is slow on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.