Optimize Binary Search for Target Position in Sorted Array

Problem :- Search Insert Position (LeetCode 35) Problem Statement :- 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 if it were inserted in order. You must write an algorithm with O(log n) runtime complexity. Approach :- Binary Search i - Uses Binary Search to efficiently find the target or its position in a sorted array. ii - Compares nums[mid] with target and adjusts search range (start or end). iii -  Loop ends when target is not found, and correct position is crossed. iv - If target > nums[mid] => mid + 1 Else => mid v - Time Complexity : O(log n) vi - Space Complexity : O(1) class Solution { public int searchInsert(int[] nums, int target) { int start = 0; int end = nums.length - 1; int mid = 0; while (start <= end) { mid = start + (end - start) / 2; if (nums[mid] == target) { return mid; } else if (nums[mid] < target) { start = mid + 1; } else { end = mid - 1; } } return (target > nums[mid]) ? mid + 1 : mid; } } Key Takeaway :- Binary Search efficiently finds the position (or insertion point) by repeatedly dividing the search space. How would you optimize this further? #Java #DSA #LeetCode #CodingJourney #LearnInPublic #SoftwareEngineering #BinarySearch

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories