101 Logo
onenoughtone

Problem Statement

Library Book Finder

You're working as a software developer for the "Grand Central Library," which houses millions of books across multiple floors. The library has recently digitized its catalog, and each book has been assigned a unique numerical code based on its location.

The library staff needs a fast and efficient way to locate books when patrons request them. Since the book codes are arranged in ascending order in the digital catalog, you've been tasked with implementing a binary search algorithm to quickly find a book's position given its code.

Your task is to implement a function that takes a sorted array of book codes and a target code, and returns the index of the target code in the array. If the target code is not found, the function should return -1.

Examples

Example 1:

Input: bookCodes = [1023, 1052, 1198, 1276, 1352, 1414, 1553], targetCode = 1276
Output: 3
Explanation: The book with code 1276 is at index 3 in the array.

Example 2:

Input: bookCodes = [2001, 2010, 2015, 2023, 2030], targetCode = 2020
Output: -1
Explanation: The book with code 2020 is not in the array, so we return -1.

Example 3:

Input: bookCodes = [3001, 3002, 3003, 3004, 3005], targetCode = 3001
Output: 0
Explanation: The book with code 3001 is at index 0 in the array.

Constraints

  • The input array will be sorted in ascending order.
  • The array length will be between 1 and 10^6.
  • The book codes will be positive integers less than 10^9.
  • The function should be implemented using a recursive binary search approach.

Problem Breakdown

To solve this problem, we need to:

  1. Binary search is a classic divide-and-conquer algorithm that reduces the search space by half in each step.
  2. The key insight is that in a sorted array, we can eliminate half of the remaining elements by comparing the target with the middle element.
  3. The recursive approach naturally divides the problem into smaller subproblems, making it a perfect fit for the Divide & Conquer pattern of recursion.
  4. Binary search has a time complexity of O(log n), which is much more efficient than linear search (O(n)) for large datasets.
ProblemSolutionCode
101 Logo
onenoughtone