
Problem
Solution
Submissions
Binary Search
Certification: Basic Level
Accuracy: 71.43%
Submissions: 7
Points: 5
Write a Java program to implement binary search algorithm. Binary search is an efficient algorithm for finding an element in a sorted array. The function should return the index of the target element if found, otherwise return -1.
Example 1
- Input: nums = [1, 3, 5, 7, 9, 11], target = 5
- Output: 2
- Explanation:
- Mid = (0 + 5) / 2 = 2 → nums[2] = 5 → target found
Example 2
- Input: nums = [1, 3, 5, 7, 9, 11], target = 6
- Output: -1
- Explanation:
- Search reduces to empty range → target not found
Constraints
- 1 ≤ nums.length ≤ 10^4
- -10^4 ≤ nums[i] ≤ 10^4
- All elements are unique and sorted
- Time Complexity: O(log n)
- Space Complexity: O(1) iterative, O(log n) recursive
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- Binary search only works on sorted arrays
- Use two pointers (left and right) to track the search range
- Calculate the middle element and compare it with the target
- Adjust the search range based on the comparison
- Can be implemented both iteratively and recursively