Modified Binary Search
Modified Binary Search
Atul kumar PK
Backend Engineer @ TakeMe Co., Ltd
Problem 1 : Order agnostic binary search
Given a sorted array of numbers, find if a given number ‘key’ is present in
the array. Though we know that the array is sorted, we don’t know if it’s
sorted in ascending or descending order. You should assume that the array
can have duplicates.
Write a function to return the index of the ‘key’ if it is present in the array,
otherwise return -1.
1. Example
1. Solution
Problem 1 : Ceiling of a Number
Write a function to return the index of the ceiling of the ‘key’. If there isn’t
any ceiling return -1.
Input: [1, 3, 8, 10, 15], key = 12
Output: 4
Explanation: The smallest number greater than or equal to '12' is '15' having index '4'.
2. Example
2. Solution
Problem 3 : Number Range
Given an array of numbers sorted in ascending order, find the range of a given
number ‘key’. The range of the ‘key’ will be the first and last position of the ‘key’
in the array.
Write a function to return the range of the ‘key’. If the ‘key’ is not present return
[-1, -1].
maxIndex = 3
Output: [1, 3]
3. Solution (call 2 times - find max and then find min index) Any optimization?
Problem 4 : Search in rotated array
Given an array of numbers which is sorted in ascending order and also rotated by
some arbitrary number, find if a given ‘key’ is present in it.
Write a function to return the index of the ‘key’ in the rotated array. If the ‘key’ is not
present, return -1. You can assume that the given array does not have any duplicates.
Input: [4, 5, 7, 9, 10, -1, 2], key = 10
Output: 4
1. If arr[start] <= arr[middle], the numbers from start to middle are sorted in ascending order.
2. Else, the numbers from middle+1 to end are sorted in ascending order.
Once we know which part of the array is sorted, it is easy to adjust our ranges. For example, if option-1 is true,
we have two choices:
1. By comparing the ‘key’ with the numbers at index start and middle we can easily find out if the ‘key’
lies between indices start and middle; if it does, we can skip the second part => end = middle -1.
2. Else, we can skip the first part => start = middle + 1.
4. Example
4. Solution
Practice problems
1. Count rotation
a. Input: [10, 15, 1, 3, 8]
b. Output: 2
2. Rotation count of a sorted and rotated array that has duplicates too?
a. Input: [3, 3, 7, 3]
b. Output: 3
3. Given an array of numbers sorted in ascending order, find the floor of a given number ‘key’.
b. Output: 3
c. Explanation : The biggest number smaller than or equal to '12' is '10' having index
'3'.