← All Exercises

Lower and Upper Bounds in a Sorted Array

basictypescript~25min

Background

Bound searches power range queries, pagination cursors, and duplicate counting without scanning the array.

Problem

Given a sorted array of numbers and a target, return a tuple with the first index where target could be inserted and the first index past the last equal element.

Input

A non-decreasing array of numbers and a target number.

Output

A two-element tuple [lower, upper] of zero-based indices between 0 and the array length.

Sample tests

Sample 1

Input: nums = [1,3,3,5,8], target = 3
Expected: [1,3]

Sample 2

Input: nums = [1,2,3], target = 4
Expected: [3,3]

Sample 3

Input: nums = [1,2,3], target = 0
Expected: [0,0]

Your solution

Learning objective

Write half-open binary searches for lower and upper bounds and use their difference to count duplicates.