Data Structures & Algorithms Binary Search
💡
Exercise 49

Search Insert Position 15 XP Easy

LeetCode Ctrl+Enter Run Ctrl+S Save

Given a sorted array of distinct integers and a target, return the index if found. If not, return the index where it would be inserted to keep the array sorted.

nums = [1,3,5,6], target = 5 → 2 (found at index 2) nums = [1,3,5,6], target = 2 → 1 (insert between 1 and 3) nums = [1,3,5,6], target = 7 → 4 (insert at end)

This is binary search with a twist — when the target isn't found, left ends up at the correct insertion position. Think about why!

💡 Pro tip: Understand this problem deeply — don't just memorize the code. Try explaining the approach out loud as if teaching a friend. If you can explain it simply, you truly understand it!

📋 Instructions
Implement `search_insert(nums, target)` using binary search. Test with: - `search_insert([1,3,5,6], 5)` → 2 - `search_insert([1,3,5,6], 2)` → 1 - `search_insert([1,3,5,6], 7)` → 4 Print all three results.
Standard binary search. When the loop ends without finding target, return `left` — it's exactly where the target should be inserted.
🧪 Test Cases
Input
search_insert([1,3,5,6], 5)
Expected
2
Test case 1
Input
search_insert([1,3,5,6], 2)
Expected
1
Test case 2
Input
search_insert([1,3,5,6], 7)
Expected
4
Test case 3
main.py
Hi! I'm Rex 👋
Output
Ready. Press ▶ Run or Ctrl+Enter.