Logo
YouTubeDiscord
Constant Time
Constant Time
/Binary Search
Binary Search
/
🍫
Binary search Vanilla to Chocolate
/
Using the Alternate Binary Search Approach (Optional)

Using the Alternate Binary Search Approach (Optional)

Alternate Approach (Optional)

class Solution:
    def search(self, nums: List[int], target: int) -> int:
        
        l, r =0,len(nums)-1
        
        while l < r:
            
            m = l + (r-l)//2
            
        
            # true value
            if nums[m] >= target:
                r = m 
            
            else:
                l = m + 1
                
               
       
        # Return the index.
        return r if nums[r] == target else -1

Complexities

Time Complexity: O(log(n))

Space Complexity: O(1)

Saves on space as we are not storing storing the variable possibleValue.

📐Understanding Time Complexity of OLog(N): Math + Intuition