Emmanuel Akinfulubi

JavaScriptArray

Find the longest increasing subarray in JavaScript

Advanced · 4 min read

Given a list of numbers, which unbroken stretch keeps going up for the longest? In [1, 2, 1, 3, 5, 2, 4, 6, 7] the answer is [2, 4, 6, 7]. This is the kind of question you ask of real data: the longest winning streak, the longest run of rising prices, the most days in a row that a number improved.

In this tutorial you will write longestIncreasingRun with one loop and two variables. Along the way you will meet two small bugs that are easy to write and hard to spot, and see how to avoid both. You should know arrays, for...of loops and the spread syntax ....

What counts as a run

A run here is a stretch of values next to each other, where each value is bigger than the one before it. "Next to each other" matters: you can't skip values. And "bigger" means strictly bigger, so 1, 1 is not increasing.

Split the example list wherever it stops going up, and you get the runs:

Output

1, 2 | 1, 3, 5 | 2, 4, 6, 7

The longest is 2, 4, 6, 7, with four values.

Two variables

Walk through the list once, and keep track of two arrays:

  • current, the run you are in right now.
  • best, the longest run you have seen so far.

For each value, either extend current or start a new run. Then, if current is now longer than best, remember it.

Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.

48 The longest increasing run

hard

Find the longest stretch of strictly increasing values. In [1, 2, 1, 3, 5, 2, 4, 6, 7] that is [2, 4, 6, 7]. Decide what a tie does.

Stuck? Three hints, smallest first
  1. 1. Keep two arrays: the run in progress, and the best one seen so far.
  2. 2. When a value is not larger than the previous one, the current run ends and a new one starts at that value.
  3. 3. Copy the current run when it becomes the best, or the two names will point at one array.

Step 1: extend or restart

A value extends the run if the run is empty or the value is bigger than the run's last value. current.at(-1) reads that last value.

Step 1

let current = [];
for (const v of [1, 2, 1, 3]) {
  if (current.length === 0 || v > current.at(-1)) current.push(v);
  else current = [v];
  console.log(v, current);
}
// 1 [ 1 ]
// 2 [ 1, 2 ]
// 1 [ 1 ]
// 3 [ 1, 3 ]

When the run breaks, the new run starts with the current value: current = [v]. That value is the first step of whatever comes next.

Step 2: the first wrong turn

It is tempting to write current = [] when the run breaks, as if starting from nothing. Watch what happens:

Step 2

let current = [];
for (const v of [1, 2, 1, 3]) {
  if (current.length === 0 || v > current.at(-1)) current.push(v);
  else current = [];
  console.log(v, current);
}
// 1 [ 1 ]
// 2 [ 1, 2 ]
// 1 []
// 3 [ 3 ]

The second 1 was thrown away, so the next run became [3] instead of [1, 3]. Every run after the first loses its opening value.

Step 3: remember the best, as a copy

Step 3

function longestIncreasingRun(xs) {
  let best = [];
  let current = [];
  for (const v of xs) {
    if (current.length === 0 || v > current.at(-1)) current.push(v);
    else current = [v];
    if (current.length > best.length) best = [...current];
  }
  return best;
}

console.log(longestIncreasingRun([1, 2, 1, 3, 5, 2, 4, 6, 7])); // [ 2, 4, 6, 7 ]

best = [...current] saves a copy of the run. The copy is important, and the next step shows why.

Step 4: why the copy matters

Arrays are shared by reference. After best = current, without the copy, the two names point at one and the same array, so any change made to current in place also changes best.

In Step 3 that happens to be harmless, because current = [v] builds a brand new array each time a run breaks. But a small, reasonable-looking edit shows the danger. Here the run is restarted by emptying the same array instead of making a new one:

Step 4

function noCopy(xs) {
  let best = [];
  let current = [];
  for (const v of xs) {
    if (current.length === 0 || v > current.at(-1)) current.push(v);
    else { current.length = 0; current.push(v); }
    if (current.length > best.length) best = current;
  }
  return best;
}

console.log(noCopy([1, 2, 3, 0, 1])); // [ 0, 1 ]

The right answer is [1, 2, 3]. When the 0 arrived, current.length = 0 emptied the array that best was also pointing at, so the saved run was wiped. The shorter run [0, 1] then got reported as the longest. best = [...current] takes a snapshot that nothing else can touch, so the function stays correct however current is handled.

Step 5: ties, equal values and edge cases

Step 5

function longestIncreasingRun(xs) {
  let best = [];
  let current = [];
  for (const v of xs) {
    if (current.length === 0 || v > current.at(-1)) current.push(v);
    else current = [v];
    if (current.length > best.length) best = [...current];
  }
  return best;
}

console.log(longestIncreasingRun([1, 2, 0, 3])); // [ 1, 2 ]
console.log(longestIncreasingRun([1, 1, 2]));    // [ 1, 2 ]
console.log(longestIncreasingRun([3, 2, 1]));    // [ 3 ]
console.log(longestIncreasingRun([]));           // []

In [1, 2, 0, 3] both runs have two values. The test is >, not >=, so a later run must be strictly longer to replace best. The earlier run wins ties.

In [1, 1, 2] the second 1 is not bigger than the first, so it starts a new run. If you want "never goes down" instead, which suits timestamps, change v > current.at(-1) to v >= current.at(-1).

A list that only goes down gives runs of one, and the first one is kept. An empty list never enters the loop, so best stays [].

One more word: this finds a stretch with no gaps, often called a subarray. The longest increasing subsequence, which may skip values, is a different and harder problem.

The full solution

The panel runs longestIncreasingRun on the example, then on a tie, on equal neighbors, on a falling list and on an empty list. The last line checks that the answer really sits unbroken inside the input. Press Run.

The answer

function longestIncreasingRun(xs) {
  let best = [];
  let current = [];
  for (const v of xs) {
    if (current.length === 0 || v > current.at(-1)) current.push(v);
    else current = [v];                       // the run ends; start again here
    if (current.length > best.length) best = [...current];   // a copy, on purpose
  }
  return best;
}

const readings = [1, 2, 1, 3, 5, 2, 4, 6, 7];
const found = longestIncreasingRun(readings);

console.log('input   :', readings);
console.log('runs    : [1,2] [1,3,5] [2,4,6,7]');
console.log('longest :', found, 'length', found.length);
console.log('a tie   :', longestIncreasingRun([1, 2, 0, 3]), '<- both are 2 long, the first wins');
console.log('strictly increasing, so equals break it:', longestIncreasingRun([1, 1, 2]));
console.log('decreasing:', longestIncreasingRun([3, 2, 1]));
console.log('empty     :', longestIncreasingRun([]));
console.log('contiguous in the input?', readings.join(',').includes(found.join(',')));

Output


      
9 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 9 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

9 checks

test('the longest run', found, [2, 4, 6, 7]);
test('and its length', found.length, 4);
test('a tie keeps the earlier run', longestIncreasingRun([1, 2, 0, 3]), [1, 2]);
test('an already increasing list is a single run', longestIncreasingRun([1, 2, 3]), [1, 2, 3]);
test('a decreasing list has runs of one', longestIncreasingRun([3, 2, 1]), [3]);
test('equal neighbours break the run, because increasing is strict', longestIncreasingRun([1, 1, 2]), [1, 2]);
test('one element is a run of one', longestIncreasingRun([5]), [5]);
test('an empty list gives an empty run', longestIncreasingRun([]), []);
test('the run really is contiguous in the input', readings.join(',').includes(found.join(',')), true);

Two details decide correctness. When the run breaks, the new run starts at the current value and not empty — write current = [] and you lose an element from every run after the first. And best = [...current] has to copy: assign the array itself and best keeps growing as current does, so a later, shorter run can end up reported as the longest.

"Strictly increasing" is a choice, and the [1, 1, 2] assertion states which one was taken. Change > to >= and you have non-decreasing runs instead, which is what you usually want for timestamps. This is the contiguous problem, not the longest increasing subsequence, which allows gaps and needs a rather different algorithm.

Common mistakes

  • Restarting with current = []. The value that broke the run is lost, so every later run is one short. Restart with [v].
  • Saving best = current without a copy. Both names then share one array, so emptying or editing current in place also changes best.
  • Using >= by accident. Equal neighbors then count as increasing, which changes the answer for [1, 1, 2].

Try it yourself

  1. Return the start index and length of the run instead of the run itself.
  2. Write longestDecreasingRun with one small change.
  3. Find the longest run where each value is exactly one more than the last, so [4, 5, 6] counts but [4, 6] does not.

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.