702. Binary Search Using Recursion

EasyRecursionRecursion

Given a sorted array of integers nums (in non-decreasing order) and an integer target, write a recursive function that returns the index of target in nums. If the target is not present, return -1. You must implement the search using recursion (no loops). If duplicates exist, returning the index of any valid occurrence is acceptable for this problem; for the test cases, the target either appears at a unique index or is absent, so the answer is unique.

Input: An integer array nums (sorted ascending) and an integer target.

Output: Return an integer: the index of target in nums, or -1 if not found.

Examples

Example 1
Input: [1,2,3,4,5], 3
Output: 2
Explanation: mid=2, nums[2]=3 equals target -> return index 2.
Example 2
Input: [1,2,3,4,5], 6
Output: -1
Explanation: Target greater than every element. Search collapses to empty range -> -1.
Example 3
Input: [-5,-3,-1,1,3,5], -1
Output: 2
Explanation: mid=2, nums[2]=-1 equals target -> return 2.

Constraints

Asked by

TCSInfosysWiproCognizantCapgemini
Solve this problem in the editor →