Locate a Target's Index in a Sorted Array Using Recursive Halving

Implement binarySearchRecursive

Given a sorted array nums and a value target, find the index of target in the array using recursion — or return -1 if it isn't present. Sortedness turns "which half could possibly contain the target?" into a question answerable in O(1): compare the target against the middle element, and an entire half of the array can be ruled out immediately, no matter how large the array is. Express that as a recursive call on whichever half survives, narrowing the window (given by a low and high bound) with every call, until either the target is found or the window collapses to nothing (the base case). Each call does a constant amount of work and halves the remaining search space, so the total number of calls needed is O(log n) — a linear scan's worst case shrinks to a logarithmic one, purely by using the fact that the array is sorted.

Example 1:

Input: nums = [2,5,8,12,16,23,38,45,56,72,91], target = 23

Output: 5

Example 2:

Input: nums = [2,5,8,12,16,23,38,45,56,72,91], target = 100

Output: -1

Example 3:

Input: nums = [2,5,8,12,16,23,38,45,56,72,91], target = 2

Output: 0

+ 3 hidden test cases run on Submit.

Constraints:

  • 1 ≤ nums.length ≤ 15
  • nums is sorted in strictly increasing order
  • -100 ≤ nums[i], target ≤ 200
  • Return the index of target if it exists, or -1 otherwise

nums =

[2, 5, 8, 12, 16, 23, 38, 45, 56, 72, 91]

target =

23