Grokking the Art of Recursion for Coding Interviews
Ask Author
Back to course home

0% completed

Vote For New Content
Solution: Binary Search
Table of Contents

Contents are not accessible

Contents are not accessible

Contents are not accessible

Contents are not accessible

Contents are not accessible

Problem Statement

Write Recursive Approach to Implement Binary Search Algorithm.

The problem is to implement the binary search algorithm using recursion. Given a sorted array and a target key, the algorithm should determine whether the key is present in the array or not.

Examples

Sr #ArrayInput KeyOutput
1[1, 2, 3, 4, 5]4True
2[2, 4, 6, 8, 10]5False
3[3, 6, 9, 12, 15]15True

Constraints:

  • 1 <= nums.length <= 10<sup>4</sup>
  • -10<sup>4</sup> < nums[i], target < 10<sup>4</sup>
  • All the integers in nums are unique.
  • nums is sorted in ascending order.

Solution

The algorithm follows a recursive approach to implement binary search. Here are the key points:

  1. Base Case: If the lower bound is greater than the upper bound, return False as the key is not found.
  2. Recursive Case:
    • Calculate the mid index between the lower and upper bounds.
    • Compare the element at the mid index with the target key.
      • If they are equal, return True as the key is found.
      • If the element at the mid index is greater than the target key, make a recursive call on the left half of the array with an updated upper bound of mid - 1.
      • If the element at the mid index is less than the target key, make a recursive call on the right half of the array with an updated lower bound of mid + 1.

The algorithm follows the principles of binary search, narrowing down the search space by half at each step. By utilizing recursion, it divides the array into smaller halves until the target key is found or the bounds become invalid.

Image

Code

Here is the code for this algorithm:

Python3
Python3

. . . .

Time and Space Complexity

The time complexity of the binary search algorithm is O(log N) as the search space is halved at each recursive step. The space complexity is O(log N) as well, considering the recursive function calls stored on the call stack.

.....

.....

.....

Like the course? Get enrolled and start learning!

Table of Contents

Contents are not accessible

Contents are not accessible

Contents are not accessible

Contents are not accessible

Contents are not accessible