LeetCode ยท #35

Search Insert Position Solution

Given a sorted array and a target, return the index if found โ€” or the index where it would be inserted.

01
Section One ยท Problem

Problem Statement

๐Ÿท๏ธ

Difficulty

Easy

๐Ÿ”—

LeetCode

Problem #35

๐Ÿ—๏ธ

Pattern

Binary Search โ€” lower bound

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 inserted to keep the array sorted. You must write an O(log n) algorithm.

Example 1
Input: nums = [1,3,5,6], target = 5 Output: 2
Example 2
Input: nums = [1,3,5,6], target = 2 Output: 1 // 2 would be inserted at index 1 (between 1 and 3)
Constraints
โ€ข 1 โ‰ค nums.length โ‰ค 10โด โ€ข -10โด โ‰ค nums[i] โ‰ค 10โด โ€ข nums contains distinct values sorted in ascending order โ€ข -10โด โ‰ค target โ‰ค 10โด
02
Section Two ยท Approach 1

Linear Scan โ€” O(n)

Walk through the array. Return the first index where nums[i] >= target. If no such index, insert at the end.

Problem: O(n) ignores sorted property. This is exactly the "lower bound" binary search โ€” find the first position where nums[i] >= target.
Java โ€” Linear Scan
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; } }
Python โ€” Linear Scan
class Solution: def searchInsert(self, nums: list[int], target: int) -> int: for i, num in enumerate(nums): if num >= target: return i return len(nums)
MetricValue
TimeO(n)
SpaceO(1)
03
Section Three ยท Approach 2

Binary Search (Lower Bound) โ€” O(log n)

This is the classic lower bound binary search. Find the leftmost position where the target could be inserted. When nums[mid] < target, move right. Otherwise, the answer is at mid or earlier โ€” move left boundary.

๐Ÿ’ก Mental model: You're looking for a seat in a sorted row. If the seat number at mid is too small, you go right. If it's equal or larger, this could be your seat โ€” but there might be an earlier one, so you keep searching left. When the search ends, left is exactly where you sit (or insert).
Algorithm
  • Step 1: left = 0, right = n (note: not n-1, because insert position could be past the end).
  • Step 2: While left < right: compute mid.
  • Step 3: If nums[mid] < target โ†’ left = mid + 1.
  • Step 4: Else โ†’ right = mid.
  • Step 5: Return left.
๐ŸŽฏ Lower bound vs exact search:
  • Standard binary search returns -1 if not found. Lower bound always returns a valid insert position.
  • The difference: use left < right (not โ‰ค) and right = mid (not mid-1).
  • This converges L and R to the insertion point.
  • This is equivalent to C++ std::lower_bound or Python's bisect.bisect_left.
04
Section Four ยท Trace

Visual Walkthrough

Trace through nums = [1, 3, 5, 6], target = 2:

Lower Bound Binary Search โ€” find insertion point
nums: [1, 3, 5, 6] target=2 Step 1: L=0,R=4,mid=2 โ†’ nums[2]=5 โ‰ฅ 2 โ†’ R=2 Step 2: L=0,R=2,mid=1 โ†’ nums[1]=3 โ‰ฅ 2 โ†’ R=1 Step 3: L=0,R=1,mid=0 โ†’ nums[0]=1 < 2 โ†’ L=1 L==R==1 โ†’ insert at index 1 Answer: 1 โœ“
05
Section Five ยท Implementation

Code โ€” Java & Python

Java โ€” Lower Bound Binary Search
class Solution { public int searchInsert(int[] nums, int target) { int left = 0, right = nums.length; while (left < right) { int mid = left + (right - left) / 2; if (nums[mid] < target) left = mid + 1; else right = mid; } return left; } }
Python โ€” Lower Bound (or bisect_left)
class Solution: def searchInsert(self, nums: list[int], target: int) -> int: left, right = 0, len(nums) while left < right: mid = (left + right) // 2 if nums[mid] < target: left = mid + 1 else: right = mid return left # One-liner: return bisect.bisect_left(nums, target)
06
Section Six ยท Analysis

Complexity Analysis

ApproachTimeSpaceTrade-off
Linear ScanO(n)O(1)Simple but ignores sorted
Lower Bound BS โ† optimal O(log n) O(1) Classic lower-bound search
07
Section Seven ยท Edge Cases

Edge Cases & Pitfalls

CaseInputWhy It Matters
Insert at start[2,4,6], target=1All elements โ‰ฅ target โ†’ left stays 0 โ†’ insert at 0.
Insert at end[2,4,6], target=7All elements < target โ†’ left reaches n โ†’ insert at end.
Exact match[2,4,6], target=4Found โ†’ return index 1. Lower bound naturally finds it.
Single element[3], target=3mid=0, nums[0]=3 โ‰ฅ 3 โ†’ R=0 โ†’ L==R==0.
โš  Common Mistake: Initializing right = n - 1 instead of right = n. The insert position can be at index n (past the end), so the search range must include it. With right = n - 1, inserting after the last element is missed.

โ† Back to Binary Search problems