Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Implement recursive binary search

Use recursion to locate a target value in a sorted list and return its index or -1 if absent.

Python practice15 minSearching & SortingIntermediateLast updated March 25, 2026

Problem statement

Given a list of numbers sorted in ascending order and a target value, implement recursive binary search to find the target's index. If the target is not found, return -1. The recursion should reduce the search interval by half each step. Assume zero-based indexing.

Task

Write a recursive binary search function that returns the index of target in a sorted list, or -1 when the target is not present.

Examples

Find existing element

Input

recursive_binary_search([1, 2, 3, 4, 5], 3)

Output

2

Middle element is 3 at index 2; recursion finds and returns its index.

Input format

Two arguments: recursive_binary_search(sorted_list, target)

Output format

An integer index (0-based) of target in the list, or -1 if not found.

Constraints

The input list is sorted in non-decreasing order. Use recursion (no iterative loops for the main search logic). Time complexity O(log n), space O(log n) due to recursion depth.

Samples

Sample 1

Input

recursive_binary_search([10, 20, 30, 40], 30)

Output

2

30 is at index 2.