Here, We see Search Insert Position problem Solution. This Leetcode problem is done in many programming languages like C++, Java, JavaScript, Python, etc. with different approaches.

Search Insert Position LeetCode Solution
Problem Statement ->
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.
Example 1: Input: nums = [1,3,5,6], target = 5 Output: 2 Example 2: Input: nums = [1,3,5,6], target = 2 Output: 1 Example 3: Input: nums = [1,3,5,6], target = 7 Output: 4
Search Insert Position Leetcode Solution C++ ->
class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
int beg = 0;
int end = nums.size()-1;
while(beg <= end){
int mid = (beg + end)/2;
if(target > nums[mid]){
beg = mid + 1;
}else if(target < nums[mid]){
end = mid - 1;
}else{
return mid;
}
}
return beg;
}
};
Code language: C++ (cpp)
Search Insert Position Leetcode 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;
}
}
Code language: Java (java)
Search Insert Position Leetcode Solution JavaScript ->
var searchInsert = function(nums, target) {
for(let i =0;i<nums.length;i++){
if(nums[i] >= target) return i;
}
return nums.length;
};
Code language: JavaScript (javascript)
Search Insert Position Leetcode Solution Python ->
class Solution(object):
def searchInsert(self, nums, target):
for i in range(len(nums)):
if(nums[i] >= target):
return i
return len(nums)
Code language: Python (python)