First element in sorted array greater than target

Given a sorted array and a target value, this problem asks to find the index of the first element in the array that is greater than the target. For example, given the array [1 , 2, 3, 4, 5] and target value 3, the output would be 2 since 2 is the index of the first element in the array (4) that is greater than the target value.

Problem

Find the index of the first element in a sorted array that is greater than a given target value.
Input: [1, 2, 3, 4, 5], target = 3
Output: 2

Solution

This solution is in C++. Our A.I. can create solutions in multiple languages.
by kayakane
#include <iostream>
#include <vector>

using namespace std;

int find_first_greater_than(vector<int>& arr, int target) {
    int left = 0;
    int right = arr.size() - 1;
    int mid;
    while (left <= right) {
        mid = left + (right - left) / 2;
        if (arr[mid] > target) {
            right = mid - 1;
        } else {
            left = mid + 1;
        }
    }
    return left;
}

int main() {
    vector<int> arr = {1, 2, 3, 4, 5};
    int target = 3;
    cout << find_first_greater_than(arr, target) << endl;
    return 0;
}

A.I. Evaluation of the Solution

The candidate's solution is complete and solves the problem. The candidate has used a binary search algorithm which is a good approach.

Evaluated at: 2022-11-23 02:16:02