Introduction to Advanced Binary Search Problems

Greetings, curious minds! Today, we'll explore binary search applications that transcend basic searching. We'll apply binary search to complex data structures, such as bitonic arrays and rotated sorted arrays, to find specific elements efficiently.

Problem 1: Searching in a Bitonic Array

Consider a bitonic array as a numerical sequence simulating the trajectory of a roller coaster — first, it rises to a peak, then descends. For example, consider the array [1, 2, 3, 4, 5, 3, 1]: its first part ascends, and the last descends, making it bitonic. Your goal is to find a value in such an array. You might walk the entire path, which is exhaustive and represents our naive approach with a time complexity of O(n)O(n). Our aim today is a more efficient method.

Efficient Approach Explained

To apply binary search, we first locate the peak of the array, then perform binary search on either side of the peak: one for the increasing sub-array and one for the decreasing sub-array.

The first step is akin to finding a vantage point at the carnival for a better view:

let start = 0, end = arr.length - 1;

// Here, we start our search for the peak, akin to scanning the crowd for higher ground.
while (start < end) {
    let mid = Math.floor((start + end) / 2);
    if (arr[mid] > arr[mid + 1]) {
        // Our peak is to the left.
        end = mid;
    } else {
        // The peak is to the right.
        start = mid + 1;
    }
}
let peak = start; // The peak is found—a place where you can see far and wide!
Solution Building: Searching the Target

Now, let's perform a targeted binary search on sub-arrays:

// Binary search on the ascending sub-array
start = 0, end = peak;
while (start <= end) {
    let mid = Math.floor((start + end) / 2);
    if (arr[mid] === target) return mid;
    else if (arr[mid] < target) start = mid + 1;
    else end = mid - 1;
}

// Binary search on the descending sub-array
start = peak, end = arr.length - 1;
while (start <= end) {
    let mid = Math.floor((start + end) / 2);
    if (arr[mid] === target) return mid;
    else if (arr[mid] > target) start = mid + 1;
    else end = mid - 1;
}
return -1; // If the target is not found in either sub-array

The searching logic for the ascending part checks if the middle element is our target and updates start or end based on how the target compares. For the descending part, the logic flips since the values are now descending.

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal