Algorithms Playbook
← All problems
EasyBinary search →Similar to: Search Insert Position

Where does it go?

Problem

Given a sorted array of distinct integers and a target, return the index of target if present. Otherwise return the index where it would be inserted to keep the array sorted. Your solution must run in O(log n).

Examples

Input: nums = [1, 3, 5, 6], target = 5

Output: 2

Input: nums = [1, 3, 5, 6], target = 2

Output: 1

It would go between 1 and 3.

Hints

    Try it first. Every hint reveals a bit more.

    Solution