Recursive Binary Search

Medium~15 min

Given a sorted array of integers nums and a target value, return the index of target using recursive binary search. If the target is not found, return -1.

Binary search works by repeatedly dividing the search space in half. Compare the target with the middle element — if they match, you are done. If the target is smaller, search the left half. If it is larger, search the right half.

You must solve this problem recursively — do not use loops.

Examples

Example 1
Input: nums = [1, 3, 5, 7, 9], target = 5
Output: 2
Explanation: 5 is at index 2 in the array.
Example 2
Input: nums = [1, 3, 5, 7, 9], target = 6
Output: -1
Explanation: 6 is not in the array, so return -1.
Example 3
Input: nums = [], target = 1
Output: -1
Explanation: An empty array cannot contain any target.

Constraints

  • 0 <= nums.length <= 10^4
  • -10^4 <= nums[i] <= 10^4
  • nums is sorted in ascending order
  • All values in nums are unique
  • You must use recursion (no loops)
Code
Ctrl+EnterRun|Ctrl+⇧+EnterSubmit
Output

Run your code to see results

Use Cmd+Enter to run