Given a nearly sorted array such that each of the n elements may be misplaced by no more than one position from the correct sorted order, search a given element in it efficiently. Report if the element is not present in the array.

An element at index i in a correctly sorted order can be misplaced by the ± 1 position, i.e., it can be present at index i-1 or i or i+1 in the input array.

 
For example,

Input:
 
nums = [2, 1, 3, 5, 4, 7, 6, 8, 9]
target = 5
 
Output: Element 5 found at index 3
 
 
Input:
 
nums = [2, 1, 3, 5, 4, 7, 6, 8, 9]
target = 10
 
Output: Element not found in the array

Practice this problem

A simple solution would be to run a linear search on the array and find the given element’s index. The problem with this approach is that its worst-case time complexity is O(n), where n is the size of the input. This solution also does not take advantage of the fact that the input is circularly sorted.

 
We can easily solve this problem in O(log(n)) time by modifying the binary search algorithm. The idea is to compare the target number with elements at A[mid-1], A[mid], and A[mid+1], where mid is the middle index of our search space A[low…high]. If the target is found, return the corresponding index; otherwise, reduce our search space to the left subarray A[low…mid-2] or right subarray A[mid+2…high] depending upon if the middle element is less than the target number or not.

The algorithm can be implemented as follows in C, Java, and Python:

C


Download  Run Code

Output:

Element 5 found at index 3

Java


Download  Run Code

Output:

Element 5 found at index 3

Python


Download  Run Code

Output:

Element 5 found at index 3

The time complexity of the above solution is O(log(n)) and doesn’t require any extra space.