All problems
0066EasyArrayBinary Search

Threshold Insert Slot

Tracked in this browser only
Write code

Trains the technique from

LeetCode 35Search Insert Position

This is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.

Same function shape, different story and different numbers.

An alerting service keeps its trigger levels in thresholds, an array of distinct integers held in increasing order. Slots are numbered from 0.

An operator wants to add the trigger level level. Report where it belongs:

  • if level is already one of the stored trigger levels, report the slot it currently occupies;
  • otherwise report the slot level would occupy after being inserted, with every later trigger level shifting one slot along so the array stays in increasing order. A level above every stored trigger level therefore belongs at slot thresholds.length.

Scanning the array end to end is too slow for the service. Your routine has to finish in time logarithmic in the length of thresholds.

Examples

Example 1

Input
thresholds = [-40, -12, 5, 18, 63], level = 18
Output
3

The level 18 is already stored at slot 3, so that slot is reported.

Example 2

Input
thresholds = [-40, -12, 5, 18, 63], level = 6
Output
3

Inserting 6 pushes 18 and 63 one slot along, so 6 lands at slot 3.

Example 3

Input
thresholds = [-40, -12, 5, 18, 63], level = 90
Output
5

Every stored level is below 90, so it is appended one past the last slot.

Constraints

  • 1 <= thresholds.length <= 10^4
  • -10^4 <= thresholds[i] <= 10^4
  • thresholds holds distinct integers in increasing order
  • -10^4 <= level <= 10^4

The signature

The editor is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.

Python
def insert_slot(thresholds: list[int], level: int) -> int:
Java
public int insertSlot(int[] thresholds, int level)
September 7
Apply