Binary Search — LeetCode 704 Python Solution
- Problem
- #704
- Pattern
- Monotonic Stack
- 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
| Measure | Complexity |
|---|---|
| Time | O(\log n), where n is the length of the array \textit{nums} |
| Space | O(1) auxiliary |
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
On study lists
This problem is on NeetCode 150 and Grind 75.
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.