Dsa
Binary Search
Easy
Find the First Occurrence of Element
You have a sorted array of integers and a target integer. Write a function to determine the index of the first occurrence of the target in the array. If the target is not found, return -1. Your solution should be efficient with a time complexity of O(log n) using binary search.
Input:
- A single line containing space-separated integers representing the sorted array.
- An integer as target to search for.
Output:
- The index of the first occurrence of the target or -1 if it is not present.
Example:
Input:
1 2 2 2 3 4 5
2
Output:
1
Key concepts
binary_searcharrayfirst_occurrence
Practise this out loud — free
Start a mock interview on THIS exact question — a voice AI interviewer opens with it, pushes back like a real onsite, then hands you an instant scorecard.
🎙 Practise this question now