Implement binary search to find the index of a target value in a sorted list of integers. If the target is found, return its index (0-based). If not found, return -1. The input list is guaranteed to be sorted in ascending order. Handle null inputs by returning -1.
Binary search is an efficient algorithm that works by repeatedly dividing the search interval in half. Compare the target with the middle element. If they match, return the middle index. If the target is less than the middle element, search the left half. If greater, search the right half. Repeat until found or the search space is empty.
Examples:
Input: sortedList = [1, 3, 5, 7, 9, 11, 13], target = 7
Output: 3
Explanation: Target 7 is found at index 3
Input: sortedList = [1, 3, 5, 7, 9, 11, 13], target = 6
Output: -1
Explanation: Target 6 is not in the list
Input: sortedList = [2, 4, 6, 8, 10], target = 2
Output: 0
Explanation: Target 2 is found at index 0 (first element)
Input: sortedList = [2, 4, 6, 8, 10], target = 10
Output: 4
Explanation: Target 10 is found at index 4 (last element)
Input: sortedList = null, target = 5
Output: -1
Explanation: Null list returns -1
Input: sortedList = [], target = 5
Output: -1
Explanation: Empty list returns -1
Welcome to Lightning Challenge!
How It Works
- • Write your solution in the code editor
- • Connect your Salesforce org to test
- • Submit to check if your solution passes
- • Use hints if you get stuck
Contest Alert
Contest runs July 1 - 31. Complete challenges to climb the leaderboard!
Only the 31 daily challenges shown during this contest count toward points. Earlier dailies don't carry over.