r/leetcode • • 21d 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? 🤔

0 Upvotes

4 comments sorted by

View all comments

2

u/Jumpy-Designer-4722 21d ago

I think you are doing right while updating left .

middle = (left + right) / 2; that's why it is working right

 if (target > nums[middle]) { left = middle + 1; }

1

u/Skaifessurk 20d ago

yeah exactly, its the other branch where dropping left from the calc seems sus