Binary Search Insert Position in Sorted Array

🚀 Day 18/30– DSA Challenge 📌 LeetCode Problem – Search Insert Position 📝 Problem Statement Given a sorted array nums and a target value, return the index if found. If not found, return the index where it would be inserted in order. 📌 Example Input: nums = [1,3,5,6] target = 2 Output: 1 Explanation: 2 should be inserted at index 1. 💡 Key Insight This is a binary search variation. 👉 If element exists → return index 👉 If not → return the position where it should be And that position is exactly where left ends after the loop. 🚀 Algorithm 1️⃣ Initialize: left = 0 right = n - 1 2️⃣ While left <= right: Find mid If equal → return mid If smaller → move left Else → move right 3️⃣ If not found → return left ✅ Java Code (Optimal O(log n)) class Solution { public int searchInsert(int[] nums, int target) { int left = 0; int right = nums.length - 1; while (left <= right) { int mid = left + (right - left) / 2; if (nums[mid] == target) { return mid; } else if (nums[mid] < target) { left = mid + 1; } else { right = mid - 1; } } return left; } } ⏱ Complexity Time Complexity: O(log n) Space Complexity: O(1) 📊 Performance ⚡ Runtime: 0 ms (Beats 100%) 💾 Memory: ~44 MB 📚 Key Learnings – Day 18 ✔ Binary Search is more than just finding elements ✔ “Insert position” problems are common variations ✔ Final value of left is very important ✔ Always avoid overflow → use mid = left + (right - left)/2 Simple problem. Strong concept. Perfect execution. Day 18 completed. Consistency continues 💪🔥 #30DaysOfCode #DSA #Java #InterviewPreparation #ProblemSolving #CodingJourney #BinarySearch #LeetCode

  • graphical user interface, text, application

To view or add a comment, sign in

Explore content categories