If you’ve ever solved coding problems on LeetCode, you’ve probably seen “Search Insert Position.” It sounds simple, but it teaches you one of the most important algorithms in computer science: Binary Search. Today, I’ll walk you through this problem like I’m explaining it to a friend who just started coding.
By the end of this article, you’ll not only understand the code but also know why it works, where it’s used in real projects, and how to avoid the common mistakes that trip up beginners.
The "Search Insert Position" problem is LeetCode #35. Here’s the task: You’re 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.
For example, if your array is and target is 5, you return 2. If the target is 2, you return 1 because 2 should go between 1 and 3.
Sounds easy, right? You could just loop through the array. But there’s a smarter way that runs much faster — Binary Search.
To get the most out of this tutorial, you should know:
If you’re brand new, don’t worry. I’ll keep things simple and explain every step.
Let’s first talk about Binary Search before we jump into code. Imagine you’re looking for a word in a dictionary. You don’t start at page 1 and flip every page. You open the middle, see if your word comes before or after, and throw away half the book. Then repeat.
That’s Binary Search. It only works on sorted data, but it’s incredibly efficient. If you have 1 million items, linear search takes up to 1 million steps. Binary Search takes at most 20.
In a normal Binary Search, we return -1 if the element isn’t found. Here, we need to return where it *should* be. That small change makes this problem perfect for learning how Binary Search boundaries work.
You might think, “When will I ever need this?” More often than you’d expect:
WHERE id > 100 in SQL, the database uses a variation of Binary Search on indexes.git bisect.So mastering this builds a foundation for system design and optimization later.
Let’s make this concrete. Here are 3 places you’ve used this logic without knowing:
| Scenario | How Binary Search Helps |
|---|---|
| Finding your name in a sorted contact list | Phone apps don’t scan every contact. They jump to the middle and narrow down. |
| Booking a seat in a sorted row | Ticket systems find the first available seat >= your preferred seat number. |
| Loading data pages in apps | When you scroll to date “15-June” in a calendar, the app binary searches the sorted events. |
Let’s solve this together. Problem: Given nums = , target = 2, find insert position.
Because the array is sorted, if nums < target, we know the target can’t be on the left. So we discard the left half. Same for the right side.
We use start = 0 and end = nums.length - 1. These mark the current search range.
while(start <= end) means we keep going until the range collapses.
mid = start + (end - start) / 2. We do this instead of (start + end) / 2 to avoid integer overflow for huge arrays.
nums == target, we found it. Return mid.target > nums, target must be on the right. So start = mid + 1.end = mid - 1.When the loop ends, start will be at the exact spot where target should be inserted. That’s the magic. We return start.
start always points to the first element that is >= target. That’s exactly the insert position definition.
Here’s the complete Java solution you asked about:
class Solution {
public int searchInsert(int[] nums, int target) {
int start = 0;
int end = nums.length - 1;
while(start <= end) {
int mid = start + (end - start) / 2;
if(nums == target) {
return mid;
}
if(target > nums) {
start = mid + 1;
} else {
end = mid - 1;
}
}
return start;
}
}
Let’s break down every line like you’re 5:
int start = 0; We begin searching from the first index.int end = nums.length - 1; And we end at the last index. For , end = 3.while(start <= end) Keep searching as long as our window has at least 1 element.int mid = start + (end - start) / 2; Find the middle index. This formula prevents overflow if start and end are huge numbers.if(nums == target) Jackpot. We found the target, so return its position.if(target > nums) Target is bigger, so it must be to the right. Move start after mid.else { end = mid - 1; } Target is smaller, so it must be to the left. Move end before mid.return start; If we exit the loop, target wasn’t found. But start is now sitting at the correct insert spot.Let’s dry-run with nums = , target = 2:
| Step | start | end | mid | nums | Action |
|---|---|---|---|---|---|
| 1 | 0 | 3 | 1 | 3 | 2 < 3, so end = 0 |
| 2 | 0 | 0 | 0 | 1 | 2 > 1, so start = 1 |
| 3 | 1 | 0 | - | - | Loop ends. Return start = 1 |
And 1 is correct, because 2 should be inserted at index 1: .
while(start < end) instead of <=, you’ll miss the case where target equals the last remaining element. Always use <= for this pattern.
These are the 4 bugs I see in 90% of beginner submissions:
start < end causes infinite loops or wrong answers when start == end. Fix: Use start <= end.mid after loop fails because mid is outdated. Fix: Return start.(start + end) / 2 can overflow for large arrays. Fix: Use start + (end - start) / 2.left and right are often clearer than start and end for Binary Search.if(nums.length == 0) return 0;mid + 1 and mid - 1. Future you will thank you.Binary Search is already O(log n) time, which is excellent. O(1) space because we only use a few variables. But here are micro-tips:
Arrays.binarySearch() is heavily optimized. But in interviews, write it yourself.start + (end - start) / 2 instead of (start + end) / 2?nums = , target = 0? Walk through it.Arrays.binarySearch() in Java handle insert position? Hint: It returns -(insertion point) - 1.start work when target isn’t found?Because the loop invariant guarantees that at the end, all elements before start are < target, and all elements after start are > target. So start is the first position where target can go.
Yes, but the problem says “distinct integers.” If duplicates exist, this returns *any* valid insert position. For “first position,” you’d change end = mid - 1 to end = mid and adjust the loop.
nums is empty?By LeetCode constraints it won’t be. In production, return 0 because you’d insert at index 0.
For sorted data, yes. For unsorted data, you can’t use Binary Search. And for tiny arrays n < 10, linear might be faster due to less overhead.
Arrays.binarySearch?Arrays.binarySearch returns the index if found, else (-insertion_point - 1). So you can get insert point with -result - 1 if result < 0.
mid - 1 and mid + 1? Why not just mid?Because we already checked nums. We know it’s not the answer, so we exclude it from the next search range.
O(1). We only use three int variables regardless of array size.
Yes, but flip the comparisons. If target < nums, go right instead of left.
No. Rotated arrays need a modified Binary Search to find the pivot first. That’s LeetCode 33.
Once you master this, try these next:
Search Insert Position teaches you the core Binary Search pattern: shrink the range by half each step using two pointers. The key insight is that when the loop ends, start points to the insert location. We covered the theory, code, dry-run, mistakes, and real-world uses.
You now have everything you need to solve Search Insert Position and explain it in an interview. The best way to lock this in is to code it yourself 3 times without looking. Then try the related problems above.
Binary Search looks simple but it’s the gateway to advanced algorithms. Get comfortable here, and trees, heaps, and graphs become easier later.
start, end, mid each loop to see it work.Got questions? Drop them in the comments and I’ll reply. Happy coding!