LeetCode 704, Easy. Topics: Array, Binary Search. View on LeetCode.
Generate this problem as a practice environment: tested reference solution, 13 parametrized pytest cases, and a playground notebook:
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. Otherwise, return -1.
You must write an algorithm with O(log n) runtime complexity.
Examples
Explanation: 9 exists in nums and its index is 4
Explanation: 2 does not exist in nums so return -1
Constraints
1 <= nums.length <= 10^4
-10^4 < nums[i], target < 10^4
- All the integers in
nums are unique.
nums is sorted in ascending order.
Solution
Reference implementation from solution.py on GitHub, full suite in test_solution.py:
Complexity
Grind 75, Grind, NeetCode 150, NeetCode 250, NeetCode All. Last modified on September 7, 2026