Binary Search in a Shifted Array |
Interview Question

Shifted Search

Course launching August 2020

Follow me on YouTube for free coding interview videos.

Users who sign up for the email list will receive an exclusive 75% discount at launch.

Your subscription could not be saved. Please try again.
Your subscription was successful! 🤓

Given a shifted array of sorted unique integers, write a function findTargetIndex that returns the index of a target value.

You are given an array of sorted integers that has been shifted by some number of spots. For example:

  • Original array: [0, 1, 2, 3, 4, 5, 6, 7, 8]
  • Shifted array: [3, 4, 5, 6, 7, 8, 0, 1, 2]

It is the same values in the same order but with the array rotated.

You can assume all the numbers in the array are unique.

If the number doesn't exist in the array, you should return -1.

const items = [3, 4, 5, 6, 7, 8, 0, 1, 2];
const target = 5;
findTargetIndex(items, target) // 2

Validate My Answer

  1. Ensure you have handled cases where the target exist and doesn't exist in the input array.

  2. Since the array is mostly sorted, you can still use a modified version of binary search to get O(log n) time.