Where does this value belong?
Inserting into a sorted list — a leaderboard, a timeline, a set of sorted filter values — needs the position, not just a yes/no answer. This is the variant of binary search that returns where a value belongs even when it is not there.
Implement insertPosition(sorted, target). sorted is an array of numbers in ascending order, possibly containing duplicates, and target is a number. Return the lowest index at which target could be inserted so the array stays sorted: that is the index of the first element greater than or equal to target, or the array's length when every element is smaller. An empty array returns 0.
Because the index must be the lowest valid one, a target that is already present returns the index of its first occurrence, not the last.
Arguments
sortednumber[]- An array of numbers in ascending order, possibly containing duplicates.
targetnumber- The value whose insertion position is wanted.
Returns
number — The lowest index at which target could be inserted so the array stays sorted.
Examples
insertPosition([1, 3, 5, 7], 4);
// 2 — the gap between 3 and 5insertPosition([1, 2, 2, 2, 5], 2);
// 1 — the first occurrence, not the lastTies on the target resolve to the lowest valid index.
insertPosition([1, 2, 3], 9);
// 3 — past the end
insertPosition([], 5);
// 0 — an empty arrayWhat it has to do
- Return the index of the first element greater than or equal to the target.
- Return the index of the first occurrence when the target is already present.
- Return the array length when the target is larger than every element.
- Return 0 for an empty array or a target smaller than every element.
- Halve the search range each step rather than scanning.
Notes
- O(log n) time, like plain binary search. This is the
lower_boundfrom C++ and the right primitive for keeping a sorted list sorted on insertion. - The key change from
binarySearchis the search space[0, length]rather than[0, length - 1], and never short-circuiting on a match — movehighdown tomidso duplicates settle on the lowest index.
Stuck? The javascript course covers everything this challenge needs.
- 1.finds the gap for a value that is not present
- 2.returns the first occurrence of a present value
- 3.returns the lowest index among duplicates
- 4.clamps to both ends of the array
- 5.handles an empty array
These assertions run in your browser the moment you hit Run. Pass all of them to claim the XP.
Discussion
Sign in to postNo comments yet. Be the first to say something.