logoNEURAL COOK
SearchAll PostsTagsNotesAuthor
logoNEURAL COOK

A posts created with Next.js and Tailwind.css

Explore

  • All posts
  • Notes
  • Snippets
  • Tags
  • RSS feed

Connect

instagramtwitterfacebookyoutubelinkedinmailgithub

© 2026 VIKI. All rights reserved.

Built with
Contents
Table Of Contents
13. Roman to Integer14. Longest Common Prefix20. Valid Parentheses26. Remove Duplicates from Sorted Array35. Search Insert Position69. Sqrt(x)70. Climbing Stairs88. Merge Sorted Array (In-Place)104. Maximum Depth of Binary Tree118. Pascal's Triangle121. Best Time to Buy and Sell Stock205. Isomorphic Strings242. Valid Anagram283. Move Zeroes345. Reverse Vowels of a String605. Can Place Flowers704. Binary Search796. Rotate String1071. Greatest Common Divisor of Strings1299. Replace Elements with Greatest Element on Right Side1431. Kids With the Greatest Number of Candies1614. Maximum Nesting Depth of the Parentheses1752. Check if Array Is Sorted and Rotated1768. Merge Strings Alternately1903. Largest Odd Number in String2965. Find Missing and Repeated Values
Code Scratch/leetcode/easy

35. Search Insert Position

1 min read
On this pageIntuition
IntuitionComplexityCode

# Intuition

Since the array is sorted, we can leverage binary search to find the target efficiently in O(log n) time.

  • If the target exists in the array, binary search will locate and return the index.
  • If not found, the correct insert position for the target is exactly where the left pointer ends up — this is where the value would maintain the sorted order.

# Complexity

Space ComplexityTime Complexity
O(1)\text{O}(1)O(1)O(log⁡n)\text{O}(\log{n})O(logn)

# Code

public int searchInsert(int[] nums, int target) {
    // Initialize binary search boundaries
    int left = 0, right = nums.length - 1;
    
    // Perform binary search
    while (left <= right) {
        int mid = (left + right) >> 1; // Same as (left + right) / 2
 
        // If target found at mid, return index
        if (nums[mid] == target) return mid;
 
        // If target is greater, discard left half
        if (nums[mid] < target) {
            left = mid + 1;
        } 
        // If target is smaller, discard right half
        else {
            right = mid - 1;
        }
    }
 
    // If not found, left is the correct insertion index
    return left;
}
 
←Previous26. Remove Duplicates from Sorted ArrayNext→69. Sqrt(x)

On this page

IntuitionComplexityCode