Sale
Summer Offer: $190/yr $99/yr
00 : 00 : 00 : 00
Get this deal
Backend Engineer Senior programming

Given a sorted array of integers, write a function to search for a target value. If the target exists in the array, return its index. If it does not, return -1. Your algorithm should have O(log n) complexity.


Function Signature


def binary_search(nums: List[int], target: int) -> int:

Constraints


  • 1 <= nums.length <= 10^4

  • -10^4 <= nums[i], target <= 10^4

  • All integers in nums are unique.


Examples


1. Input: binary_search([1, 2, 3, 4, 5], 3)
Output: 2
2. Input: binary_search([1, 2, 3, 4, 5], 6)
Output: -1
Suggested Answer

Trusted by 100+ professionals preparing for interviews

Trusted by 100+ professionals 50+ Company Question Banks 5+ Supported Languages

Practice More Questions Like This

Generate unlimited interview questions with structured answers, code runner, and AI-powered walkthroughs.

Get Started Free
Link copied to clipboard