# LeetCode 35. Search Insert Position

## Description

https://leetcode.com/problems/search-insert-position/description/

Given a sorted array 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 may assume no duplicates in the array.

Here are few examples.
`[1,3,5,6]`, 5 → 2
`[1,3,5,6]`, 2 → 1
`[1,3,5,6]`, 7 → 4
`[1,3,5,6]`, 0 → 0

## Explanation

To do a search in a sorted array, we can consider using binary search to achieve. Just by following basic binary search principle, to compare mid position value with target value constantly and we can find the target or the right place to insert the target.

## Java Solution

```class Solution {
public int searchInsert(int[] nums, int target) {
int start = 0;
int end = nums.length - 1;

while (start + 1 < end) {
int mid = start + (end - start) / 2;
if (nums[mid] == target) {
return mid;
} else if(nums[mid] < target) {
start = mid;
} else {
end = mid;
}
}

if (nums[end] < target) {
return end + 1;
} else if (nums[start] >= target) {
return start;
} else {
return end;
}
}
}```

## 4 Thoughts to “LeetCode 35. Search Insert Position”

1. Parth says:

Please do a video on 38. Count and Say leetcode problem too. I am unable to understand that.

Thanks

2. Hi GoodTecher,
You are doing a nice work on helping me to improve my problem-solving skill.
Here is one LeetCode that I need you to explain – LeetCode 278 First Bad Version.
Regards

1. Thank you Ade. Will take a look at the question 🙂