Live Batches
Masterclasses
Menu
Free Courses
Account
Login / Sign Up

Find Element in a Sorted Array

Easy Acceptance 80.00% Points 20.00

Given a sorted array of integers and a target value, return the index of the target element if it is present in the array. If the target is not found, return -1. The array is sorted in non-decreasing order, and the search should be performed efficiently using binary search.

Examples
Example 1

image Input: arr = [1,3,5,7,9], target = 7

Output: 3

Explanation: The target value 7 is present at index 3 in the array.

Example 2

image Input: arr = [2,4,6,8,10], target = 5

Output: -1

Explanation: The target value 5 is not present in the array, so return -1.

Example 3

image Input: arr = [11,22,33,44], target = 11

Output: 0

Explanation: The target value 11 is present at index 0 in the array.

Hints
Hint 1
N/A
Constraints
  • 1 = arr.length = 105
  • -104 = arr[i], target = 104
  • arr is sorted in non-decreasing order.
Companies
Apple
Topics
Binary Search
Solution.cs C#JavaPythonC++Javascript

Unlock the code editor

Sign in to write, run, and submit your solution against the full test suite.

  • Run code against sample & hidden test cases
  • Save submissions and track your streak
  • Compare with editorial & community solutions