Find First and Last Position of Element in Sorted Array

Pattern: Binary search on sorted arrays

medium

The first copy is at the lower bound of the target. The last copy is one before the lower bound of target + 1. Two binary searches, O(log n).

The problem

You are given an array sorted in increasing order, which may repeat values, and a target. Return the first and last index of the target as [first, last], or [-1, -1] if it is not there. The search must take O(log n) time. For example, [5, 7, 7, 8, 8, 10] gives [3, 4] for target 8 and [-1, -1] for target 6.

The function name searchRange matches LeetCode. Use the link above for the exact statement and limits.

Think first

  • Which yes/no test turns true exactly at the first copy of the target?
  • Which test turns true exactly after the last copy?
  • How do you tell that the target is missing?

Hints

    Brute force, and why it fails

    Find any copy with binary search, then walk left and right while the value matches. That is O(n) when the whole array is the target. Two boundary searches stay O(log n) in every case.

    The key insight

    Searching for a boundary instead of a value keeps the search O(log n) even with many copies. The first copy is one boundary, and the start of the next bigger value is the other.

    Dry run

    50lo
    71 
    72 
    83 
    84 
    105 

    nums = [5, 7, 7, 8, 8, 10] and target = 8. First, the lower bound of 8.

    Step 1 of 3

    The plan

    first = lowerBound(nums, target)
    if first == n or nums[first] != target: return [-1, -1]
    last = lowerBound(nums, target + 1) - 1
    return [first, last]
    

    Complexity

    Time
    O(log n)
    Space
    O(1)

    Two lower-bound searches.

    Edge cases

    • Empty array: [-1, -1].
    • Every value is the target: [0, n - 1].
    • Target is 2,147,483,647: target + 1 overflows a 32-bit int, so widen it first.
    I've built my logic, show the code

    Java

    class Solution {
        public int[] searchRange(int[] nums, int target) {
            int first = firstAtLeast(nums, target);
            if (first == nums.length || nums[first] != target) return new int[]{-1, -1};   // not present
            int last = firstAtLeast(nums, (long) target + 1) - 1;   // one before the first bigger value
            return new int[]{first, last};
        }
    
        private int firstAtLeast(int[] nums, long x) {     // lower bound
            int lo = 0, hi = nums.length;
            while (lo < hi) {
                int mid = lo + (hi - lo) / 2;
                if (nums[mid] >= x) hi = mid;
                else lo = mid + 1;
            }
            return lo;
        }
    }

    C++

    class Solution {
    public:
        vector<int> searchRange(vector<int>& nums, int target) {
            int first = firstAtLeast(nums, target);
            if (first == static_cast<int>(nums.size()) || nums[first] != target) return {-1, -1};   // not present
            int last = firstAtLeast(nums, static_cast<long long>(target) + 1) - 1;   // one before the first bigger
            return {first, last};
        }
    
        int firstAtLeast(vector<int>& nums, long long x) {   // lower bound
            int lo = 0, hi = static_cast<int>(nums.size());
            while (lo < hi) {
                int mid = lo + (hi - lo) / 2;
                if (nums[mid] >= x) hi = mid;
                else lo = mid + 1;
            }
            return lo;
        }
    };

    Python

    class Solution:
        def searchRange(self, nums: list[int], target: int) -> list[int]:
            first = self.first_at_least(nums, target)
            if first == len(nums) or nums[first] != target:
                return [-1, -1]                     # not present
            return [first, self.first_at_least(nums, target + 1) - 1]   # one before the first bigger value
    
        def first_at_least(self, nums: list[int], x: int) -> int:      # lower bound
            lo, hi = 0, len(nums)
            while lo < hi:
                mid = (lo + hi) // 2
                if nums[mid] >= x:
                    hi = mid
                else:
                    lo = mid + 1
            return lo

    Common mistakes

    • Walking outwards from one found copy, which is O(n) in the worst case.
    • Not checking that nums[first] really is the target.
    • Writing target + 1 in 32-bit arithmetic.

    Similar problems