Search Insert Position

Given a sorted array of distinct integers nums and a target value, return the target's index when present. Otherwise return the index where it must be…

Given a sorted array of distinct integers `nums` and a target value, return the target's index when present. Otherwise return the index where it must be inserted to preserve ascending order. Your algorithm must run in `O(log n)` time.

- `1 <= nums.length <= 10^4` - `-10^4 <= nums[i], target <= 10^4` - `nums` is strictly increasing.

Example 1: input nums = [1,3,5,6], target = 5; output 2. 5 is already in the array at index 2, so that index is returned.

Example 2: input nums = [1,3,5,6], target = 2; output 1. 2 is not present. It is larger than 1 and smaller than 3, so it belongs at index 1, between them.

Example 3: input nums = [1,3,5,6], target = 7; output 4. 7 is larger than every element, so it is inserted after the last one, at index 4 (which equals nums.length).

Category: Binary Search. Topic: binary-search. Difficulty: Easy. Patterns: binary-search.