LeetCode 35: Search Insert Position Solution in Java (Binary Search Explained)

Learn LeetCode 35 Search Insert Position in Java using Binary Search. Step-by-step explanation, code, dry run, time complexity, and interview tips.

Search Insert Position in Java: Binary Search Explained for Beginners

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.

Introduction

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.

[1][3][5][6]

Sounds easy, right? You could just loop through the array. But there’s a smarter way that runs much faster — Binary Search.

What You Will Learn

  • What Binary Search is and why it’s so fast
  • How Search Insert Position works under the hood
  • Line-by-line explanation of the Java solution
  • How to dry-run the algorithm on paper
  • Edge cases that break your code if you miss them
  • Where Binary Search is used in real software
  • How to ace interview questions on this topic

Prerequisites

To get the most out of this tutorial, you should know:

  • Basic Java syntax: loops, if-else, methods
  • What an array is and how indexing works
  • Concept of a sorted array

If you’re brand new, don’t worry. I’ll keep things simple and explain every step.

Understanding the Concept

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.

Note: Binary Search works by repeatedly dividing the search space in half. This gives it a time complexity of O(log n), which is way better than O(n) for large datasets.

Search Insert Position: The Twist

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.

Why This Topic Matters

You might think, “When will I ever need this?” More often than you’d expect:

  1. Interviews: This is a favorite first-round coding question at Google, Amazon, Meta, and startups. It tests if you understand array indexing and search algorithms.
  2. Databases: When you run WHERE id > 100 in SQL, the database uses a variation of Binary Search on indexes.
  3. Auto-complete: Typing in a search box and seeing suggestions? The list of words is sorted and Binary Search finds your prefix instantly.
  4. Version Control: Git uses Binary Search to find which commit introduced a bug with git bisect.

So mastering this builds a foundation for system design and optimization later.

Real-World Applications

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.

Step-by-Step Tutorial

Let’s solve this together. Problem: Given nums = , target = 2, find insert position.

[1][3][5][6]

Step 1: Understand What “Sorted” Gives Us

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.

[mid]

Step 2: Set Up Two Pointers

We use start = 0 and end = nums.length - 1. These mark the current search range.

Step 3: Loop While The Range Is Valid

while(start <= end) means we keep going until the range collapses.

Step 4: Find The Middle

mid = start + (end - start) / 2. We do this instead of (start + end) / 2 to avoid integer overflow for huge arrays.

Step 5: Compare and Shrink

  • If nums == target, we found it. Return mid.
  • If target > nums, target must be on the right. So start = mid + 1.
  • Else, target is on the left. So end = mid - 1.
[mid]

Step 6: What If We Never Find It?

When the loop ends, start will be at the exact spot where target should be inserted. That’s the magic. We return start.

Pro Tip: After the loop, start always points to the first element that is >= target. That’s exactly the insert position definition.

Source Code

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;
    }
}
[mid]

Code Explanation

Let’s break down every line like you’re 5:

  1. int start = 0; We begin searching from the first index.
  2. int end = nums.length - 1; And we end at the last index. For , end = 3.
  3. while(start <= end) Keep searching as long as our window has at least 1 element.
  4. int mid = start + (end - start) / 2; Find the middle index. This formula prevents overflow if start and end are huge numbers.
  5. if(nums == target) Jackpot. We found the target, so return its position.
  6. if(target > nums) Target is bigger, so it must be to the right. Move start after mid.
  7. else { end = mid - 1; } Target is smaller, so it must be to the left. Move end before mid.
  8. return start; If we exit the loop, target wasn’t found. But start is now sitting at the correct insert spot.
[1][3][5][6][mid]

Output Explanation

Let’s dry-run with nums = , target = 2:

[1][3][5][6]
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
[mid]

And 1 is correct, because 2 should be inserted at index 1: .

[1][2][3][5][6]
Warning: If you use while(start < end) instead of <=, you’ll miss the case where target equals the last remaining element. Always use <= for this pattern.

Common Errors and Fixes

These are the 4 bugs I see in 90% of beginner submissions:

  1. Off-by-one in loop condition: Using start < end causes infinite loops or wrong answers when start == end. Fix: Use start <= end.
  2. Wrong return after loop: Returning mid after loop fails because mid is outdated. Fix: Return start.
  3. Integer overflow: (start + end) / 2 can overflow for large arrays. Fix: Use start + (end - start) / 2.
  4. Forgetting array is sorted: If you try Binary Search on unsorted data, results are garbage. Always verify input constraints.

Best Practices

  • Name variables clearly: left and right are often clearer than start and end for Binary Search.
  • Handle empty array: Though LeetCode says nums length >= 1, in real code add if(nums.length == 0) return 0;
  • Write test cases: Test target smaller than all, larger than all, duplicates if allowed, and exact match.
  • Comment your logic: Explain why you do mid + 1 and mid - 1. Future you will thank you.

Performance Tips

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:

  • For primitive arrays, Binary Search is cache-friendly because of sequential access.
  • If you’re calling this method millions of times, Java’s Arrays.binarySearch() is heavily optimized. But in interviews, write it yourself.
  • Avoid recursion for this problem. Iteration is faster and avoids stack overflow risk.

Interview Questions

Beginner Level

  1. What is the time complexity of Binary Search and why?
  2. Why do we use start + (end - start) / 2 instead of (start + end) / 2?
  3. What happens if the array is not sorted?

Intermediate Level

  1. How would you modify this to find the first or last occurrence if duplicates exist?
  2. Can you solve this using recursion? What are the trade-offs?
  3. What will your code return for nums = , target = 0? Walk through it.
  4. How does Arrays.binarySearch() in Java handle insert position? Hint: It returns -(insertion point) - 1.
[1]

Frequently Asked Questions (FAQ)

1. Why does returning 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.

2. Can this work if the array has duplicates?

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.

3. What if nums is empty?

By LeetCode constraints it won’t be. In production, return 0 because you’d insert at index 0.

4. Is Binary Search always better than linear search?

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.

5. How is this different from 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.

6. Why 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.

[mid]

7. What’s the space complexity?

O(1). We only use three int variables regardless of array size.

8. Can I use this for descending sorted arrays?

Yes, but flip the comparisons. If target < nums, go right instead of left.

[mid]

9. Will this work for a rotated sorted array?

No. Rotated arrays need a modified Binary Search to find the pivot first. That’s LeetCode 33.

Once you master this, try these next:

  • LeetCode 34: Find First and Last Position of Element in Sorted Array
  • LeetCode 704: Binary Search - the classic version
  • Floor and Ceil in a Sorted Array
  • Search in Rotated Sorted Array
  • Square Root using Binary Search

Summary

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.

Conclusion

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.

Next Steps

  1. Copy the code and run it on LeetCode 35.
  2. Modify it to print start, end, mid each loop to see it work.
  3. Solve “First Bad Version” next — it’s the same pattern.
  4. Bookmark this page and revisit before interviews.

Got questions? Drop them in the comments and I’ll reply. Happy coding!

Post a Comment

Oops!
It seems there is something wrong with your internet connection. Please connect to the internet and start browsing again.
AdBlock Detected!
We have detected that you are using adblocking plugin in your browser.
The revenue we earn by the advertisements is used to manage this website, we request you to whitelist our website in your adblocking plugin.
NextGen Digital Welcome to WhatsApp chat
Howdy! How can we help you today?
Type here...