Skip to content

Instantly share code, notes, and snippets.

@KeshariPiyush24
Last active September 21, 2024 05:29
Show Gist options
  • Save KeshariPiyush24/0336ff9f877cff545e11c6ec6ac48dab to your computer and use it in GitHub Desktop.
Save KeshariPiyush24/0336ff9f877cff545e11c6ec6ac48dab to your computer and use it in GitHub Desktop.
Binary Search

Question: 704 Binary Search

Intution:

Time Complexity: $$O(log(n))$$

Space Complexity: $$O(1)$$

Solution:

class Solution {
    public int search(int[] nums, int target) {
        int n = nums.length;
        int lo = 0;
        int hi = n - 1;
        while (lo <= hi) {
            int mid = lo + (hi - lo) / 2;
            if (nums[mid] < target) lo = mid + 1;
            else if (nums[mid] > target) hi = mid - 1;
            else return mid;
        }   
        return -1;
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment