Find First Occurrence
EasyPractice library · +10 XPbinary searcharrayssearching
Given a sorted array of N integers, and a target integer X, find the index of the first occurrence of X in the array. If X is not present in the array, return -1. Indices are 0-based.
Input
The first line contains two integers N and X, separated by a space. The second line contains N space-separated integers, representing the sorted array.
Output
Print a single integer: the 0-based index of the first occurrence of X, or -1 if X is not found.
Constraints
1 <= N <= 1000 -10^9 <= X <= 10^9 Array elements are sorted in non-decreasing order.
Time limit 1 s (native code; slower languages get more)Memory 256 MB15 hidden tests
Example 1
Input
7 5 1 2 3 5 5 5 8
Output
3
The target 5 first appears at index 3.
Example 2
Input
5 10 1 2 3 4 5
Output
-1
The target 10 is not in the array.
Hints
# Read the input from stdin and print the answer.
import sys
def main():
data = sys.stdin.read().split()
# your code here
main()
Example 1 input
7 5 1 2 3 5 5 5 8
Example 2 input
5 10 1 2 3 4 5