
Problem
Solution
Submissions
Binary Search Implementation
Certification: Basic Level
Accuracy: 0%
Submissions: 0
Points: 8
Write a JavaScript program to implement binary search algorithm to find the target value in a sorted array. Return the index of the target if found, otherwise return -1.
Example 1
- Input: nums = [-1,0,3,5,9,12], target = 9
- Output: 4
- Explanation:
- We search for target 9 in the sorted array.
- Using binary search, we check the middle element and narrow down the search space.
- We find that 9 exists at index 4 in the array.
- Therefore, we return index 4.
- We search for target 9 in the sorted array.
Example 2
- Input: nums = [-1,0,3,5,9,12], target = 2
- Output: -1
- Explanation:
- We search for target 2 in the sorted array.
- Using binary search, we systematically eliminate half the array in each iteration.
- After checking all possible positions, 2 is not found in the array.
- Therefore, we return -1 to indicate the target is not present.
- We search for target 2 in the sorted array.
Constraints
- 1 ≤ nums.length ≤ 10^4
- -10^4 < nums[i], target < 10^4
- All integers in nums are unique
- nums is sorted in ascending order
- Time Complexity: O(log n)
- Space Complexity: O(1)
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
- Use two pointers: left starting at 0 and right starting at array length - 1
- Calculate the middle index as (left + right) / 2 in each iteration
- Compare the middle element with the target value
- If middle element equals target, return the middle index
- If middle element is less than target, search in the right half
- If middle element is greater than target, search in the left half
- Continue until left pointer exceeds right pointer