Last updated on March 7th, 2025 at 10:50 pm
Here, we see the Search Insert Position LeetCode Solution. This Leetcode problem is solved using different approaches in many programming languages, such as C++, Java, JavaScript, Python, etc.
List of all LeetCode Solution
Topics
Array, Binary Search
Level of Question
Easy

Search Insert Position LeetCode Solution
Table of Contents
1. 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
2. Coding Pattern Used in Solution
The provided code implements a solution to the “Search Insert Position” problem, where the goal is to find the index at which a target value should be inserted into a sorted array to maintain its order. If the target already exists in the array, the index of the target is returned.
3. Code Implementation in Different Languages
3.1 Search Insert Position 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; } };
3.2 Search Insert Position 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.3 Search Insert Position JavaScript
var searchInsert = function(nums, target) { for(let i =0;i<nums.length;i++){ if(nums[i] >= target) return i; } return nums.length; };
3.4 Search Insert Position Python
class Solution(object): def searchInsert(self, nums, target): for i in range(len(nums)): if(nums[i] >= target): return i return len(nums)
4. Time and Space Complexity
Time Complexity | Space Complexity | |
C++ | O(log n) | O(1) |
Java | O(n) | O(1) |
JavaScript | O(n) | O(1) |
Python | O(n) | O(1) |
- The C++ code is more efficient in terms of time complexity due to the use of binary search.
- The Java, JavaScript, and Python codes are simpler but less efficient, as they use linear search.
- All implementations have the same space complexity (O(1)) since no additional data structures are used.
- The C++ implementation is optimal for large arrays due to its logarithmic time complexity.
- The Java, JavaScript, and Python implementations are easier to understand but less efficient for large inputs.