881725. upper and lower bounds of an element

Basic

Upper and Lower Bounds of an Element

Summary

Given a sorted array, find the upper and lower bounds of a target element. The problem requires you to return the indices of the first and last occurrences of the given element in the array. The array is sorted in ascending order.

Detailed Explanation

To solve this problem, we can use the following algorithm:

  1. Initialize two pointers, low and high, to the start and end of the array respectively.
  2. Calculate the middle index of the current subarray using (low + high) / 2.
  3. Compare the element at the middle index with the target element.
  4. If the elements are equal, update the lower bound by moving low up to the middle index, and repeat steps 2-4 until the elements are no longer equal.
  5. Once the elements are no longer equal, move high down to the previous middle index, and repeat steps 2-4 until the elements are equal again or high is less than low.
  6. The lower bound is now at low, and the upper bound is at high - 1.

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

Here's a step-by-step breakdown:

          +---------------+
          |         low    |
          +---------------+
                  |
                  v
+---------------+       +---------------+
|  elements      |       |  elements     |
|  (0, 1, 2, ...  |       |  (... , x, y, z)|
|  )            |       |  )           |
+---------------+       +---------------+
                  ^
                  |
          +---------------+
          |        high    |
          +---------------+

Optimized Solutions

Java

View on GeeksforGeeks
public int[] upperAndLowerBounds(int[] arr, int target) {
    int low = binarySearch(arr, target);
    if (low == -1) return new int[] {-1, -1};
    int high = low;
    while (arr[high] == target) high++;
    return new int[]{low, high-1};
}

private int binarySearch(int[] arr, int target) {
    int low = 0, high = arr.length - 1;
    while (low <= high) {
        int mid = (low + high) / 2;
        if (arr[mid] == target) return mid;
        else if (arr[mid] < target) low = mid + 1;
        else high = mid - 1;
    }
    return -1;
}

DevExCode

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

© 2026 DevExCode. All rights reserved.