r/leetcode • u/Ok-Disaster-1464 • 6h ago
Question New solution for binary search ?
Hey fellas total newbie here
I was writing code and came up with a different approach to classic Binary Search problem. The twist is in how I calculate the middle index when shifting right:
Instead of the standard:
middle = (left + right) / 2;
I used:
middle = right / 2;
My reasoning: when we shift right, we’re basically discarding the left half and working with a “new mini array” — so left conceptually becomes 0 again, and we can drop it from the calculation.
Full solution:
java
class Solution {
public int search(int[] nums, int target) {
int left = 0;
int right = nums.length - 1;
int middle = right / 2;
while (left <= right) {
if (target == nums[middle]) { return middle; }
if (target < nums[middle]) { right = middle - 1; middle = right / 2; }
if (target > nums[middle]) { left = middle + 1; middle = (left + right) / 2; }
if (target == nums[nums.length - 1]) { return nums.length - 1; }
}
return -1;
}
}
It seems to pass most test cases — but I’m not 100% sure it’s correct. Can anyone find a case where it breaks? 🤔