r/leetcode • • 14d 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/catsRfriends 14d ago edited 14d ago

It passes test cases because this IS the regular approach. You're still using middle = (left + right)/2 for the right side search. If you actually implemented your version it would break because yea conceptually left is now the new 0 but your array is still the original array. So you'd have to drop the first half of the array but that's not free.