878168. Search in an almost Sorted Array

Medium

Here is a detailed Markdown blog post for the problem "Search in an almost Sorted Array":

Search in an Almost Sorted Array

Summary

This problem involves searching for an element in an array that is almost sorted. The array may have some elements out of order, but overall it remains mostly sorted. We need to find a way to efficiently search the array and return the index of the target element.

The key concepts involved are binary search and sorting.

Detailed Explanation

To solve this problem, we can start by recognizing that the array is almost sorted, meaning most elements are in order. This allows us to use binary search as our foundation. However, when an element is out of order, we need to handle it differently.

Here's a step-by-step breakdown of the solution:

  1. Initialization: Start by initializing two pointers, low and high, to represent the range of elements in the array.
  2. Binary Search: Perform a binary search on the array using the low and high pointers as our bounds. For each iteration, calculate the mid-point and check if it's equal to the target element.
  3. Handling Out-of-Order Elements: If the mid-point is not equal to the target element, we need to handle out-of-order elements. Check if the element before or after the mid-point is in order. If it's in order, update our low and high pointers accordingly.
  4. Repeat Binary Search: Continue performing binary searches with updated low and high pointers until we find the target element.
  5. Return Index: Once we've found the target element, return its index.

Time complexity: O(log n) (where n is the size of the array) Space complexity: O(1)

Optimized Solutions

Java

View on GeeksforGeeks
public int searchAlmostSortedArray(int[] arr, int target) {
    int low = 0;
    int high = arr.length - 1;
    
    while (low <= high) {
        int mid = low + (high - low) / 2;
        
        if (arr[mid] == target) {
            return mid;
        }
        
        if (mid > 0 && arr[mid - 1] < target && target < arr[mid]) {
            // element before mid is out of order, move high pointer
            high = mid - 1;
        } else if (mid < arr.length - 1 && arr[mid + 1] > target && target > arr[mid]) {
            // element after mid is out of order, move low pointer
            low = mid + 1;
        } else {
            // binary search on the remaining range
            low = mid + 1;
            high = high - (high - low) / 2;
        }
    }
    
    return -1; // not found
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.