EasyNo. 0704
Binary Search — LeetCode 704 Python Solution
- Pattern
- Monotonic Stack
- Topics
- Array, Binary Search
- On study lists
- NeetCode 150 and Grind 75
- Reading time
- 2 min
- Source
- leetcode.com
The problem
Given an array of integers nums which is sorted in ascending order, and an integer target, write a function to search target in nums. If target exists, then return its index.
Example
- Input
- nums = [-1,0,3,5,9,12], target = 9
- Output
- 4
- Explanation
- 9 exists in nums and its index is 4
Python solution
class Solution:
def search(self, nums: List[int], target: int) -> int:
l, r = 0, len(nums) - 1
while l < r:
mid = (l + r) >> 1
if nums[mid] >= target:
r = mid
else:
l = mid + 1
return l if nums[l] == target else -1Complexity
- Time
- O(log n)where n is the length of the array nums
- Space · auxiliary
- O(1)
Pattern: Monotonic Stack
Answer "what is the next greater element" for every position in one pass. LeetCode 704. Binary Search is filed here because the reference solution below belongs to the algorithm family this hub collects, even though its LeetCode tags point elsewhere.
The monotonic stack guide has the Python template for the pattern and the 225 LeetCode problems that use it.
Related problems
| No. | Problem | Difficulty |
|---|---|---|
| 0173 | Binary Search Tree Iterator | Medium |
| 1038 | Binary Search Tree to Greater Sum Tree | Medium |
| 0004 | Median of Two Sorted Arrays | Hard |
| 0033 | Search in Rotated Sorted Array | Medium |
| 0034 | Find First and Last Position of Element in Sorted Array | Medium |
| 0035 | Search Insert Position | Easy |
Frequently asked questions
- How hard is LeetCode 704. Binary Search?
LeetCode 704. Binary Search is rated Easy on LeetCode.
- What is the time complexity of LeetCode 704. Binary Search?
The Python solution on this page runs in O(log n), where n is the length of the array \textit{nums}.
- What is the space complexity of LeetCode 704. Binary Search?
The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 704. Binary Search cover?
LeetCode 704. Binary Search is tagged Array and Binary Search on LeetCode.