New Dish on the Menu

Easybinary searchAlso known as Search Insert Position

A café menu lists dishes from cheapest to most expensive. Prices are in cents, so 420 means 4.20, and two dishes can cost the same.

The cook adds a new dish. The printer needs to know which line it goes on so the menu stays sorted. If dishes already have that exact price, the new one goes before them, so it 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 cheaper than 500. The first price of 500 or more is 575, at index 3.

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, at index 1. Index 3 would also keep the menu sorted, but the 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 at the end. That takes O(n) time, which means up to 100,000 checks for each new dish.

A plain binary search that stops at the first equal price is wrong here: in the second example it first lands on index 2, one of the two 420s, and 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