Lower Bound (First Index >= k)

medium Searching and Sorting

Problem

The array is sorted in ascending order. Print the smallest index i where a[i] >= k. If every value is smaller than k, print n (the array size).

Constraints

  • 1 <= n <= 10^5

Examples

Input

5
1 2 4 4 7
4

Output

2

Solutions

Best approachTime O(log n)Space O(1)

This is the base of many binary searches. The range [low, high) always contains the answer. Each step halves the range, so the time is O(log n). In Java the safe middle is low + (high - low) / 2.

Same code works in Java810172125Basic features only, so nothing changes between versions.
/*
 * Problem : Search in an array.
 * Input   : n, then n integers, then k.
 * Output  : The index.
 * Approach: Binary search with a half-open range.
 * Time    : O(log n)
 * Space   : O(1)
 * Java    : 8 or newer.
 */
import java.util.Scanner;

public class Main {
    // This method solves the task. It receives the input and returns the answer.
    static int solve(int[] a, int k) {
        // Step 1: The answer is in [low, high]. high = n means "no such index".
        int low = 0;
        int high = a.length;

        while (low < high) {
            // Step 2: Look at the middle. (low + (high - low) / 2 cannot overflow.)
            int mid = low + (high - low) / 2;

            // Step 3: If a[mid] is too small, the answer is on the right. Otherwise it is mid or on the left.
            if (a[mid] < k) {
                low = mid + 1;
            } else {
                high = mid;
            }
        }
        return low;
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int size = scanner.nextInt();
        int[] a = new int[size];
        for (int i = 0; i < size; i++) {
            a[i] = scanner.nextInt();
        }
        int k = scanner.nextInt();
        System.out.println(solve(a, k));
    }
}
Hints (1)
  1. What does high = n mean?