Search an element in biotonic array

dsa

Feb 5, 2025 at 05:00 am

An array is said to be biotonic if it contains distinct integers such that, the array is monotonically increasing upto index k and then monotonically decreasing.

If the array is plotted on a graph, it forms a mountain-like structure.

blog image

The naive approach is to use Linear Search, which runs in O(N) time. The time complexity can be reduced to O(log(N)) using Binary Search.

Incorrect Algorithm

Edit (5th Feb) : The following algorithm and code is incorrect for the given problem.

This algorithm is incorrect, because I assumed that, target will surely lie in sorted half, but since in the other half, the element can be present, the following algorithm fails.

I found this mistake by dry-running the code for target==4 on the given array.

blog image

In every iteration, check which half is sorted, then if target lies in the sorted half move in its direction else move in opposite direction.

Correct Algorithm

The correct algorithm for this problem is:

The following problems can also be solved by using same approach:

  1. Find maximum element in a biotonic array.
  2. Find minimum element in a rotated sorted array.
  3. Search an element in a rotated sorted array.

Refer to the code for the above problems here