Skip to content
AI360Xpert
Back to Binary Search
Easy

Search Insert Position

Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. You must write an algorithm with `O(log n)` runtime complexity.

Examples

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

Constraints

  • 1 <= nums.length <= 10^4
  • -10^4 <= nums[i] <= 10^4
  • nums contains distinct values sorted in ascending order.
  • -10^4 <= target <= 10^4

Approach

Iterate through the array. If the current element is greater than or equal to the target, return its index. If the loop finishes without finding such an element, the target should be inserted at the end of the array.

Complexity Analysis

Time Complexity
O(n)
Space Complexity
O(1)

This approach does not meet the O(log n) time complexity requirement.

Solution.java
class Solution {    public int searchInsert(int[] nums, int target) {        for (int i = 0; i < nums.length; i++) {            if (nums[i] >= target) {                return i;            }        }        return nums.length;    }}