Logo
    Logo

    ©️ 2020-2026, Akhil Abraham.

    LinkedInGitHubMediumX
    Akhil Abraham
    Akhil Abraham
    /Posts
    Posts
    /LeetCode
    LeetCode
    /
    LeetCode
    /0704 - Binary Search
    0704 - Binary Search
    0704 - Binary Search
    0704 - Binary Search

    0704 - Binary Search

    Difficulty
    Easy
    Language
    Python
    URL
    https://leetcode.com/problems/binary-search/

    Solution 1 - Iterative Binary Search

    Given a sorted array of integers and a target value, search for the target using binary search. Return its index if found, otherwise return -1. We maintain two pointers (left and right) and repeatedly check the middle element, narrowing the search space by half each iteration.

    TimeComplexity:O(log⁡n)TimeComplexity: O(\log n)TimeComplexity:O(logn)
    SpaceComplexity:O(1)SpaceComplexity: O(1)SpaceComplexity:O(1)

    Solution 2 - Recursive Binary Search

    Same approach but implemented recursively. A helper function takes the current search bounds and calls itself with a narrowed range until the target is found or the search space is exhausted.

    TimeComplexity:O(log⁡n)TimeComplexity: O(\log n)TimeComplexity:O(logn)
    SpaceComplexity:O(log⁡n)SpaceComplexity: O(\log n)SpaceComplexity:O(logn)
    """ 0704.1 - Solution 1 - Iterative Binary Search """
    
    #####################################################################################
    # Imports
    #####################################################################################
    from typing import List
    
    #####################################################################################
    # Classes
    #####################################################################################
    class Solution:
        """Solution Class"""
    
        def search(self, nums: List[int], target: int) -> int:
            """Binary Search Function"""
            left, right = 0, len(nums) - 1
    
            while left <= right:
                mid = (left + right) // 2
    
                if nums[mid] == target:
                    return mid
                elif nums[mid] < target:
                    left = mid + 1
                else:
                    right = mid - 1
    
            return -1
    
    
    #####################################################################################
    # Functions
    #####################################################################################
    def testcase():
        """Test Function"""
        print(Solution().search([-1, 0, 3, 5, 9, 12], 9))   # Expected: 4
        print(Solution().search([-1, 0, 3, 5, 9, 12], 2))    # Expected: -1
        print(Solution().search([5], 5))                       # Expected: 0
    
    
    #####################################################################################
    # Main
    #####################################################################################
    if __name__ == "__main__":
        testcase()
    
    """ 0704.2 - Solution 2 - Recursive Binary Search """
    
    #####################################################################################
    # Imports
    #####################################################################################
    from typing import List
    
    #####################################################################################
    # Classes
    #####################################################################################
    class Solution:
        """Solution Class"""
    
        def search(self, nums: List[int], target: int) -> int:
            """Binary Search Function"""
            return self._binary_search(nums, target, 0, len(nums) - 1)
    
        def _binary_search(self, nums: List[int], target: int, left: int, right: int) -> int:
            """Recursive Helper"""
            if left > right:
                return -1
    
            mid = (left + right) // 2
    
            if nums[mid] == target:
                return mid
            elif nums[mid] < target:
                return self._binary_search(nums, target, mid + 1, right)
            else:
                return self._binary_search(nums, target, left, mid - 1)
    
    
    #####################################################################################
    # Functions
    #####################################################################################
    def testcase():
        """Test Function"""
        print(Solution().search([-1, 0, 3, 5, 9, 12], 9))   # Expected: 4
        print(Solution().search([-1, 0, 3, 5, 9, 12], 2))    # Expected: -1
        print(Solution().search([5], 5))                       # Expected: 0
    
    
    #####################################################################################
    # Main
    #####################################################################################
    if __name__ == "__main__":
        testcase()