Emmanuel Akinfulubi

JavaScriptSearching

Find the insertion index in a sorted array in JavaScript

Intermediate · 3 min read

You have a sorted list and a new value. Where should the value go so the list stays sorted? A leaderboard adding a new score, a calendar adding an event, and a price list adding a product all need this answer. The position is called the insertion index.

In this tutorial you will find it with a small change to binary search, so it stays fast on long lists. You will write two versions, one that goes before any equal values and one that goes after, and then use the pair to count duplicates. You should know how binary search works first. The differences are explained step by step.

Answers are gaps, not items

Normal binary search returns an item's index. The insertion index is a gap between items. A list of 6 items has 7 gaps, numbered 0 to 6:

Gaps in [1, 3, 3, 3, 7, 9]

 gap: 0   1   2   3   4   5   6
       1   3   3   3   7   9

Inserting 5 goes in gap 4, between the last 3 and the 7. Inserting 0 goes in gap 0, and inserting 99 goes in gap 6, after the end. So the answer can equal length, which is not an index of any item.

Two answers when the value is already there

Inserting another 3 could go in gap 1 (before all the 3s) or gap 4 (after them). Both keep the list sorted. The leftmost one is often called the lower bound and the rightmost the upper bound.

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

3 Find the insertion point for a value

fair

In a sorted list, find where a value should go to keep the order, whether or not it is already present.

Stuck? Three hints, smallest first
  1. 1. This is binary search with the equality case removed, so it never stops early.
  2. 2. When the loop ends, low is the insertion point.
  3. 3. Two variants: leftmost position, or rightmost. They differ only in one comparison.

Step 1: change the boundaries

Because the answer can be length, high starts at sorted.length, not length - 1. The range is now "gaps from low to high", and the loop runs while there is more than one possible gap, so it uses <:

JavaScript

const sorted = [1, 3, 3, 3, 7, 9];
let low = 0;
let high = sorted.length;
console.log(low, high); // 0 6

Step 2: never stop early

In normal binary search you return when you hit the target. Here, hitting a 3 doesn't tell you which gap is the leftmost, so you keep narrowing. If the middle value is smaller than the target, the gap must be to its right. Otherwise the gap is at the middle or to its left, so high = mid, keeping the middle as a possibility:

Step 2

function lowerBound(sorted, target) {
  let low = 0;
  let high = sorted.length;
  while (low < high) {
    const mid = low + Math.floor((high - low) / 2);
    if (sorted[mid] < target) low = mid + 1;
    else high = mid;
  }
  return low;
}
const sorted = [1, 3, 3, 3, 7, 9];
console.log(lowerBound(sorted, 3));  // 1
console.log(lowerBound(sorted, 5));  // 4
console.log(lowerBound(sorted, 0));  // 0
console.log(lowerBound(sorted, 99)); // 6
console.log(lowerBound([], 1));      // 0

When the loop ends, low and high meet at the answer.

Step 3: the wrong turn

If you reuse plain binary search's high = mid - 1, you can throw away the right gap:

JavaScript

function wrong(sorted, target) {
  let low = 0;
  let high = sorted.length;
  while (low < high) {
    const mid = low + Math.floor((high - low) / 2);
    if (sorted[mid] < target) low = mid + 1;
    else high = mid - 1;
  }
  return low;
}
console.log(wrong([1, 3, 3, 3, 7, 9], 3)); // 0, but 3 belongs at gap 1

The middle item might be the first 3, and gap mid is just before it. Subtracting 1 skips past it.

Step 4: the upper bound

To go after any equal values, also move right when the middle value equals the target. The only change is < becoming <=:

Step 4

function upperBound(sorted, target) {
  let low = 0;
  let high = sorted.length;
  while (low < high) {
    const mid = low + Math.floor((high - low) / 2);
    if (sorted[mid] <= target) low = mid + 1;
    else high = mid;
  }
  return low;
}
console.log(upperBound([1, 3, 3, 3, 7, 9], 3)); // 4

Step 5: use the answers

Subtract the two bounds to count how many times a value appears, without scanning the list:

Step 5

function lowerBound(sorted, target) {
  let low = 0;
  let high = sorted.length;
  while (low < high) {
    const mid = low + Math.floor((high - low) / 2);
    if (sorted[mid] < target) low = mid + 1;
    else high = mid;
  }
  return low;
}
function upperBound(sorted, target) {
  let low = 0;
  let high = sorted.length;
  while (low < high) {
    const mid = low + Math.floor((high - low) / 2);
    if (sorted[mid] <= target) low = mid + 1;
    else high = mid;
  }
  return low;
}
const sorted = [1, 3, 3, 3, 7, 9];
console.log(upperBound(sorted, 3) - lowerBound(sorted, 3)); // 3
const inserted = [...sorted];
inserted.splice(lowerBound(inserted, 5), 0, 5);
console.log(inserted); // [ 1, 3, 3, 3, 5, 7, 9 ]

splice(index, 0, value) removes nothing and inserts value at index. The list is still sorted afterwards. [...sorted] makes a copy first, so the original isn't changed.

The full solution

The panel has both bounds, counts the 3s, and inserts 5 into a copy of the list. Press Run and compare the two bounds for 3.

The answer

// Leftmost: inserts before any equal values.
function lowerBound(sorted, target) {
  let low = 0;
  let high = sorted.length;          // note: length, not length - 1
  while (low < high) {
    const mid = low + Math.floor((high - low) / 2);
    if (sorted[mid] < target) low = mid + 1;
    else high = mid;
  }
  return low;
}

// Rightmost: inserts after any equal values.
function upperBound(sorted, target) {
  let low = 0;
  let high = sorted.length;
  while (low < high) {
    const mid = low + Math.floor((high - low) / 2);
    if (sorted[mid] <= target) low = mid + 1;   // <= is the only change
    else high = mid;
  }
  return low;
}

const sorted = [1, 3, 3, 3, 7, 9];

console.log('lowerBound(3):', lowerBound(sorted, 3));
console.log('upperBound(3):', upperBound(sorted, 3));
console.log('how many 3s  :', upperBound(sorted, 3) - lowerBound(sorted, 3));

// Inserting keeps the order.
const inserted = [...sorted];
inserted.splice(lowerBound(inserted, 5), 0, 5);
console.log('after inserting 5:', inserted);

Output


      
8 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 8 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

8 checks

test('before the run of equals', lowerBound(sorted, 3), 1);
test('after the run of equals', upperBound(sorted, 3), 4);
test('the gap counts the duplicates', upperBound(sorted, 3) - lowerBound(sorted, 3), 3);
test('a value below everything goes first', lowerBound(sorted, 0), 0);
test('a value above everything goes last', lowerBound(sorted, 99), 6);
test('an absent middle value', lowerBound(sorted, 5), 4);
test('inserting there keeps it sorted', inserted, [1, 3, 3, 3, 5, 7, 9]);
test('an empty list inserts at 0', lowerBound([], 1), 0);

The pair is more useful than either alone: upperBound - lowerBound counts how many times a value occurs, in log time. Note high = sorted.length rather than length - 1, and while (low < high) rather than <= — the boundaries differ from plain binary search because the answer is a gap between elements, not an element.

Common mistakes

  • Starting high at length - 1. Then "after the last item" can never be the answer, and 99 would land at gap 5.
  • Writing high = mid - 1. It can skip the correct gap. Keep high = mid.
  • Using <= in the loop condition. With high = mid, the range can stop shrinking once low equals high, and the loop runs forever.

Try it yourself

  1. Write insertSorted(list, value) that returns a new sorted list with the value added.
  2. Use the two bounds to write contains(sorted, value): it's there if the bounds differ.
  3. Find how many values in [1, 3, 3, 3, 7, 9] are less than 7 using one call.

Keep practising

Newsletter

New writing, when it lands.

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