avatar

superorange0707

  • Homepage
  • Tag
  • Category
Home Leetcode-35 -Search Insert Position
ๆ–‡็ซ 

Leetcode-35 -Search Insert Position

Posted 2025-04-9
4~6 min read

[35 -Search Insert Position]

๐Ÿ”— LeetCode Link


Problem Description

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.


Idea

Since the array is sorted, binary search is the most efficient choice (O(log n)).


Logic

  1. Define your search range
  2. Use a loop (while (left <= right) or while (left < right))
  3. Calculate mid, check if target is found
  4. change to the boundary accordingly

Code (Java - Closed Interval)

class Solution {
    public int searchInsert(int[] nums, int target) {

        int left = 0; int right = nums.length - 1;

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


Code (Java - Half-Open Interval)

class Solution {
    public int searchInsert(int[] nums, int target) {

        int left = 0; int right = nums.length;

        while(left < right){
            int mid = left + ((right - left)/2);
            
            if(nums[mid] < target){
                left = mid + 1;
            }
            else if(nums[mid] > target){
                right = mid;
            }
            else{
                return mid;
            }
        }
        return right;
    }
}
Leetcode, Binary Search
Share

Further Reading

Apr 23, 2025

283 - Move Zero

[283 - Move Zero] ๐Ÿ”— LeetCode Link Problem Description Given an integer array nums, move all 0's to the end of it while maintaining the relative order

Apr 23, 2025

27 - Remove Element

[27 - Remove Element] ๐Ÿ”— LeetCode Link Problem Description Given an integer array nums and an integer val, remove all occurrences of val in nums in-pl

Apr 23, 2025

26 - Remove Duplicates from Sorted Array

[26 - Remove Duplicates from Sorted Array] ๐Ÿ”— LeetCode Link Problem Description Given an integer array nums sorted in non-decreasing order, remove the

OLDER

Fix Personal Website

NEWER

Leetcode-69 - Sqrt(x)

Recently Updated

  • Migrating Jenkins SCM Using GitLab from Bitbucket: SCM URL Bulk Replacement
  • 283 - Move Zero
  • 27 - Remove Element
  • 26 - Remove Duplicates from Sorted Array
  • Migrating from Bitbucket to GitLab? Hereโ€™s how to keep your teams moving without missing a beat!

Trending Tags

Course two pointer Binary Tree Hash SQL Leetcode Error Recording Gitlab Bitbucket Devops

Contents