Search Insert Position - Array - Easy - LeetCode
💻 coding

Search Insert Position - Array - Easy - LeetCode

1 min read 130 words
1 min read
ShareWhatsAppPost on X
  • 1The algorithm finds the index of a target value in a sorted array or the position where it can be inserted.
  • 2It assumes no duplicates in the array, ensuring unique positions for each value.
  • 3The solution has a time complexity of O(log n) and a space complexity of O(1).

AI-generated summary · May not capture all nuances

Key Insight
AskGif

"The algorithm finds the index of a target value in a sorted array or the position where it can be inserted."

Search Insert Position - Array - Easy - LeetCode

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.

Example 1:

Input: [1,3,5,6], 5 Output: 2 Example 2:

Input: [1,3,5,6], 2 Output: 1 Example 3:

Input: [1,3,5,6], 7 Output: 4 Example 4:

Input: [1,3,5,6], 0 Output: 0

public class Solution {
 public int SearchInsert(int[] nums, int target) {
 int l = 0;
 int r = nums.Length-1;
 int mid = 0;
 while(l<=r){ 
 mid = l + (r-l)/2;
 Console.WriteLine($"{l} : {r} : {mid}");
 if(nums[mid]>target){
 r = mid-1;
 }
 else if(nums[mid]<target){
 l = mid+1;
 }
 else if(nums[mid] == target){
 return mid;
 }
 }
 
 return nums[mid]>target?mid:mid+1;
 
 }
}

Time Complexity: O(logn)

Space Complexity: O(1)

Enjoyed this article?

Share it with someone who'd find it useful.

ShareWhatsAppPost on X

sumitc91

Published on 25 September 2020 · 1 min read · 130 words

Part of AskGif Blog · coding

You might also like