mediumBinary SearchPattern: Binary Search

Binary Search in Sorted Array Solution

Problem Statement

You are given a sorted array of integers and a target integer. Implement a function to find the index of the target integer in the array using binary search. If the target is not found, return -1.

Examples

Example 1:
Input:{"low":1,"high":5,"target":3}
Output:3
Explanation: The target 3 is at index 2 in a 0-indexed list [1,2,3,4,5]
Example 2:
Input:{"low":1,"high":5,"target":6}
Output:-1
Explanation: The target 6 is not in the list [1,2,3,4,5]

Constraints

  • The input array is sorted.
  • The array must have at least one element.
Time: O(log n) Space: O(1)
We can use a binary search algorithm to find the target identifier in O(log n) time complexity

Run, Test & Submit Code

Ready to practice this challenge? Launch our interactive compilation environment with compiler validation.

Solve on Interactive Workspace

Tested Solutions

No solution code is currently loaded.
Complete this code in the workspace editor.