Diwali Offer!Flat 20% OFF
Enroll Now
PrakalpanaLive online tech training

56. Search Insert Position

EasyDay 17 of 60Binary Search

Given a sorted array nums of distinct integers and a value target, return the index of target if it is present. If it is not, return the index where it would be inserted so that the array stays sorted. The solution must be O(log n).

Example 1
Input: nums = [1,3,5,6], target = 5
Output: 2
Example 2
Input: nums = [1,3,5,6], target = 2
Output: 1
2 would go between 1 and 3.
Example 3
Input: nums = [1,3,5,6], target = 7
Output: 4
7 goes after every element.
Constraints
  • 1 <= nums.length <= 10^4
  • -10^4 <= nums[i], target <= 10^4
  • `nums` is sorted and has distinct values
Hints
Frequently asked at: Amazon, Apple, Adobe, Cognizant
Ctrl + Enter runs the examples

Not sure what to learn next?

A 1-on-1 session with an industry mentor and a roadmap built for you. How it works

  1. 1Discuss your goals
  2. 2Get a personal plan
  3. 3Start learning
Book for β‚Ή200/ 30 min