
Problem
Solution
Submissions
Binary Search Algorithm
Certification: Advanced Level
Accuracy: 100%
Submissions: 3
Points: 15
Write a Python function that implements the binary search algorithm to find a target element in a sorted list. The function should return the index of the target if found, or -1 if the target is not in the list. Implement both iterative and recursive versions of the algorithm.
Example 1
- Input: sorted_list = [1, 3, 5, 7, 9, 11, 13, 15], target = 7
- Output: 3
- Explanation:
- Step 1: Take the input list and target.
- Step 2: Perform binary search.
- Step 3: Return the index of the target if found, else -1.
Example 2
- Input: sorted_list = [2, 4, 6, 8, 10, 12], target = 5
- Output: -1
- Explanation:
- Step 1: Take the input list and target.
- Step 2: Perform binary search.
- Step 3: Return the index of the target if found, else -1.
Constraints
- The input list is sorted in ascending order.
- The list can contain only integers.
- 0 ≤ list length ≤ 10^6
- Time Complexity: O(log n), where n is the length of the list.
- Space Complexity: O(1) for iterative version, O(log n) for recursive version (due to call stack).
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 involves repeatedly dividing the search interval in half
- Compare the target with the middle element of the array
- If the target matches, return the index
- If the target is less than the middle element, search the left half
- If the target is greater than the middle element, search the right half
- Base case for recursive version: empty search interval or target found
- Handle edge cases like empty lists properly