Close Menu
    Code and Debug
    • Home
    • Our Courses
    • Blog
    • About Us
    • Contact Us
    Facebook X (Twitter) Instagram YouTube WhatsApp
    • Home
    • Our Courses
    • Blog
    • About Us
    • Contact Us
    Facebook Instagram YouTube LinkedIn WhatsApp
    Code and Debug – BlogCode and Debug – Blog
    Code and Debug – BlogCode and Debug – Blog
    Home»Data Structures & Algorithms»Search Insert Position | Leetcode 35 | Explained in Python
    Data Structures & Algorithms

    Search Insert Position | Leetcode 35 | Explained in Python

    Anirudh KhuranaBy Anirudh Khurana2 July 2025No Comments3 Mins Read
    Share Facebook Twitter Pinterest LinkedIn Tumblr Reddit Telegram Email
    Featured image of question to search insert position on leetcode
    Share
    Facebook Twitter LinkedIn Pinterest Email

    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.

    You must write an algorithm with O(log n) runtime complexity.

    Here’s the [Problem Link] to begin with.

    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

    Constraints:

    • 1 <= nums.length <= 104
    • -104 <= nums[i] <= 104
    • nums contains distinct values sorted in ascending order.
    • -104 <= target <= 104
    Contents:
     [show]
    • Brute Force Solution (Linear Scan)
      • Intuition & Approach
      • Code Implementation
      • Code Explanation
      • Time & Space Complexity
      • Conclusion
    • Optimal Solution (Binary Search – Lower Bound)
      • Intuition & Approach
      • Code Implementation
      • Code Explanation
      • Time & Space Complexity
      • Conclusion

    Brute Force Solution (Linear Scan)

    Intuition & Approach

    Walk the array from left to right.

    • At the first element that is ≥ target, return its index.
    • If you finish the loop, target belongs at the end, so return len(nums).

    Code Implementation

    class Solution:
        def searchInsert(self, nums, target):
            # Scan each element once
            for i in range(len(nums)):
                if nums[i] >= target:      # found position or exact match
                    return i
            return len(nums)               # insert after the last element
    Python

    Code Explanation

    • The loop examines every element until a suitable slot appears.
    • Worst-case touches all n elements.

    Time & Space Complexity

    • Time: O(n)
    • Space: O(1)

    Conclusion

    Straightforward but not efficient for large arrays.


    Optimal Solution (Binary Search – Lower Bound)

    Intuition & Approach

    Binary search for the first index where nums[index] ≥ target.

    • Keep variables low and high bounding the current search range.
    • Track ans, the best insertion index seen so far, starting at n (meaning “end of array”).
    • On each iteration:
      • Compute mid.
      • If nums[mid] ≥ target, record mid in ans and move high left to see if an earlier position qualifies.
      • Otherwise (nums[mid] < target) move low right.

    Code Implementation

    class Solution:
        def searchInsert(self, nums: List[int], target: int) -> int:
            n = len(nums)
            low, high = 0, n - 1
            ans = n                     # default insert position = end
    
            while low <= high:
                mid = (low + high) // 2  # midpoint of the window
    
                if nums[mid] >= target:
                    ans = mid            # nums[mid] is a valid (or exact) position
                    high = mid - 1       # keep searching left half
                else:                    # nums[mid] < target
                    low = mid + 1        # search right half
    
            return ans                   # final insertion index
    Python

    Code Explanation

    • ans always stores the smallest index found so far where nums[index] ≥ target.
    • Once low surpasses high, no better position exists, so return ans.

    Time & Space Complexity

    • Time: O(log n)
    • Space: O(1)

    Conclusion

    The binary-search method halves the search space each iteration, achieving logarithmic performance with only a few variables, ideal for production use and coding interviews alike.

    Join our Advance DSA COURSE

    For any changes to the article, kindly email at code@codeanddebug.in or contact us at +91-9712928220.

    Array Binary Search
    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email
    Previous ArticleImplement Upper Bound
    Next Article Ceil The Floor | Binary Search Implementation
    Anirudh Khurana
    • Website

    Anirudh Khurana is the founder of Code and Debug, an Indian EdTech platform that helps students and working professionals crack coding interviews and move into data and AI roles. He teaches DSA, Python, SQL, data engineering and machine learning through live bootcamps and his YouTube channel, Code and Debug, which has over 50,000 subscribers. Every guide on this blog is written or reviewed by him and tested with real code.

    Related Posts

    Data Structures & Algorithms

    DSA Interview Cheat Sheet: All Patterns You Need to Know

    4 April 2026
    Data Structures & Algorithms

    Symmetric Tree | Leetcode 101 | Recursive DFS Approach

    2 September 2025
    Data Structures & Algorithms

    Binary Tree Right Side View | Leetcode 199 | BFS and DFS Approaches

    2 September 2025
    Add A Comment
    Leave A Reply Cancel Reply

    Categories
    • AI & Machine Learning (4)
    • Data Structures & Algorithms (241)
      • Beginner (82)
      • Expert (52)
      • Intermediate (106)
    • Pandas (1)
    • Python (1)
    • Resume (1)
    • SQL (1)
    Recent Posts

    Confusion Matrix in Machine Learning: An Interactive Guide

    21 October 2026

    100 SQL Interview Questions with Queries and Answers (Freshers to Experienced)

    17 October 2026

    Logistic Regression in Machine Learning: Explained Visually (with Python)

    17 October 2026

    Linear Regression in Machine Learning: Explained Visually (with Python)

    17 October 2026

    100 Python Interview Questions and Answers for Freshers and Experienced (Free PDF)

    17 October 2026
    Facebook Instagram YouTube LinkedIn WhatsApp
    © 2025 Code and Debug. All rights reserved.

    Type above and press Enter to search. Press Esc to cancel.