All problems

Problem 13

Binary Search

Easy · 10 pts · Array, Binary Search

Problem

You are given an array of N integers sorted in non-decreasing order and a target value. Print the zero-based index of the first occurrence of the target, or -1 if the target is not in the array. The array may contain repeated values, so when the target appears several times you must report its leftmost position. Binary search does this in O(log N) steps: when the middle element is greater than or equal to the target, keep searching the left half (remembering the position if it matched); otherwise search the right half.

Input

First line: integer N. Second line: N sorted space-separated integers. Third line: target.

Output

Print the first index of the target, or -1 if it is absent.

Constraints

1 <= N <= 100000; -1000000000 <= array[i], target <= 1000000000

Example input

6
1 2 4 4 5 9
4

Example output

2

Explanation

The array is 1 2 4 4 5 9 and the target is 4. The value 4 appears at indices 2 and 3; the first of these is index 2, so the answer is 2.

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: Remove Duplicates from Sorted Array Next: Merge Two Sorted Arrays