Cracking Advanced Interview Problems with Binary Search

Introduction to the Lesson

Today, we're delving into the important topic of advanced interview problems revolving around Binary Search. You're likely familiar with the concept of Binary Search – it's an efficient algorithm for finding a specific target in a sorted list by repetitively dividing the search interval in half. Today, we are going to reinforce our understanding by tackling complex data science interview problems using Binary Search.

Problem 1: Search in a Rotated Sorted Array

Imagine a sorted array of integers that has been rotated at an unknown pivot point. This list maintains its sorted order but now starts from a random position. Your task is to find a specific target value within this array and return its index. If the target isn't present, return -1.

For example, the initial sorted array could be [1, 2, 4, 5, 8, 9, 11, 15], but after a single rotation it'd become [8, 9, 11, 15, 1, 2, 4, 5].

Example Application: Picture a server system where processes are listed in ascending order based on their IDs. Suppose a disruption rotates this list. Now, the system needs to find a process using a specific ID. A standard binary search isn't sufficient as the list, though sorted, starts at an arbitrary point.

Naive Approach: A straightforward solution involves scanning each element in the array until we find a match or exhaust the list. This linear search approach is simple but computationally expensive for large lists - its time complexity is O(n)O(n).

Problem 1: Efficient Approach

Instead of linear search, binary search can provide a faster solution with a logarithmic time complexity of O(log⁡n)O(\log n). This approach narrows down the search space by half at each step. The challenge in this case, caused by the array rotation, is determining which half of the list to contract at each step.

Defining the search area borders with left and right pointers (both inclusive, i.e. the [left, right] interval), we calculate and examine the midpoint. If the midpoint equals our target - success! However, if not, we have four scenarios for updating left and right pointers to narrow down the search space:

  • Midpoint value is equal to the target - our job is done, return the midpoint.
  • Both the target and midpoint are in the first half of the array (before the rotation point) - the target lies within the left half (from left to mid - 1).
    • To check whether both the target and midpoint lie in the first half, we check that nums[left] <= nums[mid] and nums[left] <= target < nums[mid].
  • The target and midpoint are in the second half (after the rotation point) - the target lies within the right half (mid + 1 to right).
    • To check whether both the target and midpoint lie in the second half, we check that nums[mid] <= nums[right] and nums[mid] < target <= nums[right].
  • The midpoint falls into the first half while the target is in the second half - the target is located in the right half.
    • To check whether the midpoint falls into the first half and the target falls into the second half, we check that nums[mid] > nums[right] (the target can't fall into the first half anymore, as this scenario is covered in case 3).
  • Otherwise, the midpoint falls into the second half, and the target lies in the first - our target should be in the left half.

Let's translate this into Python:

Python
def search_rotated(nums, target):
    left, right = 0, len(nums) - 1
    while left <= right:
        mid = (left + right) // 2
        if nums[mid] == target:
            return mid
        if nums[left] <= nums[mid] and nums[left] <= target < nums[mid]:
            right = mid - 1
        elif nums[mid] <= nums[right] and nums[mid] < target <= nums[right]:
            left = mid + 1
        elif nums[mid] > nums[right]:
            left = mid + 1
        else:
            right = mid - 1
    return -1

This function will successfully handle all the scenarios and provide an efficient way to perform binary search in a rotated sorted array.

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