New Dish on the Menu

Easybinary searchAlso known as Search Insert Position

A small café prints its menu with dishes listed from cheapest to most expensive. Prices are stored in cents, so 420 means 4.20. Two dishes can cost the same.

The cook has a new dish and a price for it. The printer needs to know which line the new dish goes on so the menu stays sorted. If other dishes already have that exact price, the new one is listed before them, so the newest dish gets seen first.

Your task

Write insertPosition(prices, price). prices is sorted from smallest to largest and may contain repeats. Return the index where price should be inserted: the first index whose price is greater than or equal to price. If every price is smaller, return prices.length.

Do not change the list. An empty menu returns 0. Aim for O(log n).

insertPosition(prices: int[], price: int) → int

Examples

Example 1
Input
prices = [350, 420, 420, 575, 890]
price = 500
Output
3
Why

350, 420 and 420 are all cheaper than 500. The first price that is 500 or more is 575, at index 3, so the new dish goes there and pushes 575 down a line.

Example 2
Input
prices = [350, 420, 420, 575, 890]
price = 420
Output
1
Why

Two dishes already cost 420. The new one goes before both of them, at index 1. Index 3 (after them) would be a valid sorted spot too, but the café's rule says before.

Constraints

  • 0 ≤ prices.length ≤ 100,000
  • 1 ≤ prices[i], price ≤ 100,000
  • prices is sorted in non-decreasing order.
Start with brute force

Walk from the start and return the first index whose price is at least price, or n if you reach the end.

That is O(n): up to 100,000 checks for one dish. A plain binary search that stops as soon as it finds an equal price is faster but wrong here: in the second example its first look lands on index 2, one of the two 420s, and it returns 2 instead of 1.

Hints

0 of 4 shown

Walkthrough and solution

Unlocks when you pass every test. Stuck for a while? Looking is fine too, as long as you then close it and write the code yourself.

Ctrl+Enter runs

Run your code to see results here. Run checks the examples. Submit checks every test, including hidden edge cases.

Write code