
At Google, security systems often search sorted event IDs or rule identifiers quickly. Write a function that uses binary search to find a target integer in a sorted array.
Return the index of target if it exists in the array. If it does not exist, return -1.
nums: a list of integers sorted in ascending ordertarget: an integer to search fortarget in nums, or -1 if not foundYour solution should run in O(log n) time.
Example 1
nums = [-1, 0, 3, 5, 9, 12], target = 94nums[4] = 9, so return 4.Example 2
nums = [-1, 0, 3, 5, 9, 12], target = 2-12 does not appear in the array.0 <= len(nums) <= 10^5-10^9 <= nums[i], target <= 10^9nums is sorted in strictly increasing ordernums = [-1, 0, 3, 5, 9, 12], target = 9Output4WhyThe value `9` is present at index `4`.nums = [-1, 0, 3, 5, 9, 12], target = 2Output-1WhyThe value `2` is not in the sorted array.nums = [7], target = 7Output0WhyThe array has one element, and it matches the target.0 <= len(nums) <= 10^5-10^9 <= nums[i] <= 10^9-10^9 <= target <= 10^9nums is sorted in strictly increasing orderExpected time complexity is O(log n)def binary_search(nums, target):