BudiBadu Logo
00:00

Binary Search Target Index

Binary Search Easy 1 views

Given a sorted array of integers in ascending order and a target value, write a function to find the index of the target value in the array using binary search. If the target is not present in the array, return -1.

Problem Details: The input array is guaranteed to be sorted in ascending order with no duplicate elements. Your task is to implement a binary search algorithm to locate the target value efficiently. Binary search works by repeatedly dividing the search interval in half. If the target value is found, return its index; otherwise, return -1. The solution should handle edge cases, such as an empty array or a target value not present in the array.

Example 1:

Input: nums = [-1,0,3,5,9,12], target = 9
Output: 4
Explanation: The target value 9 is found at index 4 in the array.

Example 2:

Input: nums = [-1,0,3,5,9,12], target = 2
Output: -1
Explanation: The target value 2 is not present in the array, so return -1.

Example 3:

Input: nums = [], target = 5
Output: -1
Explanation: The array is empty, so return -1.

Related Problems

No related problems found

Comments (0)

Join the Discussion

Share your thoughts, ask questions, or help others with this problem.

BudiBadu Logo

Binary Search Target Index

Binary Search Easy 1 views

Given a sorted array of integers in ascending order and a target value, write a function to find the index of the target value in the array using binary search. If the target is not present in the array, return -1.

Problem Details: The input array is guaranteed to be sorted in ascending order with no duplicate elements. Your task is to implement a binary search algorithm to locate the target value efficiently. Binary search works by repeatedly dividing the search interval in half. If the target value is found, return its index; otherwise, return -1. The solution should handle edge cases, such as an empty array or a target value not present in the array.

Example 1:

Input: nums = [-1,0,3,5,9,12], target = 9
Output: 4
Explanation: The target value 9 is found at index 4 in the array.

Example 2:

Input: nums = [-1,0,3,5,9,12], target = 2
Output: -1
Explanation: The target value 2 is not present in the array, so return -1.

Example 3:

Input: nums = [], target = 5
Output: -1
Explanation: The array is empty, so return -1.

00:00
Loading editor...
Test Results

Run your code to see test results

Click the Submit button to execute your solution

Related Problems

No related problems found

Comments (0)

Join the Discussion

Share your thoughts, ask questions, or help others with this problem.