Algo-Sim › Binary Search

Find First and Last Position of Element in Sorted Array

Medium · Binary Search · step through it in Java, Python and C++ on your own input

Find the range of indices holding target in a sorted array with two boundary binary searches.

Problem

Given an array of integers nums sorted in non-decreasing order, find the starting and ending position of a given target value. If target is not found, return [-1, -1]. The algorithm must run in O(log n) time.

Constraints

Edge cases to test

Follow-up questions

Why two searches instead of one plus a linear scan?
Scanning from a hit is O(k) for k copies, O(n) in the worst case. Two boundary searches stay O(log n).
How do you count occurrences?
upper_bound − lower_bound: O(log n).

Solution

Java

public int[] searchRange(int[] nums, int target) {
    return new int[] { bound(nums, target, true), bound(nums, target, false) };
}

private int bound(int[] nums, int target, boolean first) {
    int lo = 0, hi = nums.length - 1, ans = -1;
    while (lo <= hi) {
        int mid = lo + (hi - lo) / 2;
        if (nums[mid] == target) {
            ans = mid;
            if (first) hi = mid - 1;
            else lo = mid + 1;
        } else if (nums[mid] < target) lo = mid + 1;
        else hi = mid - 1;
    }
    return ans;
}

Python

def search_range(nums, target):
    return [bound(nums, target, True), bound(nums, target, False)]


def bound(nums, target, first):
    lo, hi, ans = 0, len(nums) - 1, -1
    while lo <= hi:
        mid = lo + (hi - lo) // 2
        if nums[mid] == target:
            ans = mid
            if first: hi = mid - 1
            else: lo = mid + 1
        elif nums[mid] < target: lo = mid + 1
        else: hi = mid - 1
    return ans

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    vector<int> searchRange(vector<int> &nums, int target) {
        return vector<int>{bound(nums, target, true), bound(nums, target, false)};
    }

    int bound(vector<int> &nums, int target, bool first) {
        int lo = 0, hi = int(nums.size()) - 1, ans = -1;
        while (lo <= hi) {
            int mid = lo + (hi - lo) / 2;
            if (nums[mid] == target) {
                ans = mid;
                if (first)
                    hi = mid - 1;
                else
                    lo = mid + 1;
            } else if (nums[mid] < target)
                lo = mid + 1;
            else
                hi = mid - 1;
        }
        return ans;
    }
};

More Binary Search problems