First and Last position of an element in a sorted array


find-first-and-last-position-of-element-in-sorted-array


Problem Statement

Given an array of integers nums sorted in non-decreasing order, find the starting and ending position of a given target value.

If the target is not found in the array, return [-1, -1].

You must write an algorithm with O(log n) runtime complexity.

Examples:

Constraints:


Intuition

The array is sorted, and we need to find both the first and last occurrence of the target. A simple linear search would be O(n), which violates the time complexity requirement.

Since we are working with a sorted array and aiming for O(log n), binary search must be used. However, standard binary search only finds a single occurrence. To solve this, we modify binary search to find:


Approach

  1. Create a helper method find that performs a binary search.

  2. Pass a flag isFirst to determine whether to look for the first or last occurrence.

  3. In the find method:

    • If a match is found, store the index in potAns (potential answer).

    • Continue searching:

      • If isFirst is true, search the left half (end = mid - 1).

      • Else, search the right half (start = mid + 1).

  4. In the main method:

    • Call find with isFirst = true for the first position.

    • If found, call find again with isFirst = false for the last position.

    • If not found, return [-1, -1].


Code in Java

class Solution {
    public int[] searchRange(int[] nums, int target) {
        int first = find(nums, target, true);
        if (first != -1) {
            int second = find(nums, target, false);
            return new int[]{first, second};
        }
        return new int[]{-1, -1};
    }

    private int find(int[] nums, int target, boolean isFirst) {
        int start = 0;
        int end = nums.length - 1;
        int potAns = -1;

        while (start <= end) {
            int mid = start + (end - start) / 2;

            if (nums[mid] == target) {
                potAns = mid;
                if (isFirst) {
                    end = mid - 1; // keep searching left
                } else {
                    start = mid + 1; // keep searching right
                }
            } else if (nums[mid] > target) {
                end = mid - 1;
            } else {
                start = mid + 1;
            }
        }

        return potAns;
    }
}

Time and Space Complexity


Dry Run

Input:

nums = [5, 7, 7, 8, 8, 10], target = 8

First Call (isFirst = true):

Second Call (isFirst = false):

Output: [3, 4]


Conclusion

This problem demonstrates how to extend binary search to find boundary positions (first and last occurrences) of a target in a sorted array. The key is to modify the search direction even after finding the target to ensure we locate the extreme ends.

Using this dual binary search pattern is efficient and scalable for large arrays, satisfying the O(log n) constraint.