Binary Search for Insert Position in Sorted Array

🚀 Day 8 – DSA Daily Series Today’s Problem: Search Insert Position (LeetCode 35) Today I solved another interesting problem that uses the concept of Binary Search on a sorted array. 🧠 Problem Given a sorted array of distinct integers and a target value, return the index if the target is found. If the target is not found, return the index where it should be inserted to maintain the sorted order. Example: Input: nums = [1,3,5,6], target = 5 Output: 2 Example: Input: nums = [1,3,5,6], target = 2 Output: 1 💡 Approach I solved this using Binary Search. Steps followed: • Initialize two pointers low and high • Calculate the middle index mid • Compare nums[mid] with the target • If target is greater → move to the right half • If target is smaller → move to the left half • If not found, the low pointer gives the correct insert position ⏱ Complexity Time Complexity: O(log n) Space Complexity: O(1) 🔎 Key Learning Binary Search is not just for searching — it can also help determine the correct position to insert elements efficiently in a sorted array. Continuing the DSA Daily Series — improving problem-solving skills one problem at a time. 🚀 #DSA #LeetCode #Python #Algorithms #BinarySearch #CodingJourney

  • graphical user interface, text

To view or add a comment, sign in

Explore content categories