Where a new price fits

binary search

Where a new price fits

Zillow Python Interview Question

Zillow keeps each neighborhood's sale prices in a list sorted from lowest to highest. When a new sale comes in, it must be placed so the list stays sorted.

Write a function insert_position(prices, new_price) that returns the position where the new price should go. If the same price is already in the list, return the position of the first copy.

Asked of

  • Data Analyst
  • Data Engineer
  • Data Scientist
  • ML Engineer
  • AI Engineer

Example 1

Input

prices = [300, 450, 600, 750], new_price = 500

Output

2

Example 2

Input

prices = [300, 450, 450, 600], new_price = 450

Output

1

Explanation

In the first example, 500 goes between 450 and 600, at position 2. In the second example, 450 is already in the list at position 1, so that is where the new sale goes.

Submit also runs 4 hidden test cases that check edge cases.