DDSA Solutions

Search in an almost Sorted Array

Advertisement

Intuition

Search in array where each element may be off by at most 1 position. Modified binary search.

Algorithm

  1. 1Binary search: check mid, mid-1, mid+1. If found: return. If arr[mid-1] > target: hi=mid-2. Else lo=mid+2.

Common Pitfalls

  • Must check three positions at each step. O(log n) with slightly larger constant.
Search in an almost Sorted Array.java
Java
// Approach: Modified binary search: check mid, mid-1, mid+1 for each step since element may be one off.
// Time: O(log n) Space: O(1)

class Solution {
    public int findTarget(int arr[], int target) {
        int left = 0;
        int right = arr.length - 1;

        while (left <= right) {
            int mid = left + (right - left) / 2;

            // Check if element is at mid, mid-1 or mid+1
            if (arr[mid] == target) {
                return mid;
            }

            if (mid > 0 && arr[mid - 1] == target) {
                return mid - 1;
            }

            if (mid < arr.length - 1 && arr[mid + 1] == target) {
                return mid + 1;
            }

            // Decide which half to go into
            if (arr[mid] < target) {
                left = mid + 2; // Skip both mid and mid+1
            } else {
                right = mid - 2; // Skip both mid and mid-1
            }
        }

        return -1; // Target not found
    }
}
Advertisement
Was this solution helpful?