Search⌘ K
AI Features

Problem: Search Insert Position

Understand how to apply binary search to a sorted array of distinct integers to find a target value's index or the correct insertion position. This lesson guides you through the logic and code implementation ensuring efficient O(log n) runtime and constant space usage for searching and insertion tasks in Java.

Statement

You are given a sorted array nums consisting of distinct integers, along with an integer target. If target exists in nums, return its index. Otherwise, return the index at which target would need to be inserted to maintain the array’s sorted order.

Your solution must achieve O(logn)O(\log n) runtime complexity.

Constraints:

  • 11 \leq nums.length 104\leq 10^4 ...