Last updated on October 10th, 2024 at 02:04 am

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.

*List of all LeetCode Solution*

*List of all LeetCode Solution*

## Topics

Array, Binary Search

## Level of Question

Easy

**Search Insert Position LeetCode Solution**

## Table of Contents

**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 = 5Output:2Example 2:Input:nums = [1,3,5,6], target = 2Output:1Example 3:Input:nums = [1,3,5,6], target = 7Output:4

**1. 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; } };

**2. 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; } }

**3. 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; };

**4. 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)