Search⌘ K
AI Features

Binary Search

Explore advanced binary search techniques to efficiently locate a target integer within sorted arrays. Understand the problem constraints and practice implementing solutions that return correct indices or -1 when the target is absent. Gain hands-on experience to improve problem-solving skills in preparation for coding interviews.

Statement

We are given an array of integers, nums, sorted in ascending order, and an integer value, target. If the target exists in the array, return its index. If the target does not exist, return -1.

Constraints:

  • 11\leq nums.length \leq 10310^3

  • 104-10^4\leq nums[i] , target \leq 10410^4

  • All integers in nums are unique.

  • nums is sorted in ascending order.

Example

Understand the problem

Let’s take a moment to make sure you’ve correctly understood the problem. The quiz below helps you check if you’re solving the correct problem:

Binary Search

1.

Find the index of the number 60 from the following array using binary search.

array = [-10, 11, 60, 70]

Also, calculate the number of comparisons required to find the number.

A.

index: 0, steps: 2

B.

index: 1, steps: 1

C.

index: 2, steps: 2

D.

index: 2, steps: 3


1 / 4

Figure it out!

We have a game for you to play. Rearrange the logical building blocks to develop a clearer understanding of how to solve this problem.

Sequence - Vertical
Drag and drop the cards to rearrange them in the correct sequence.

1
2
3
4

Try it yourself

Implement your solution in the following coding playground.

Go
usercode > main.go
package main
func binarySearch(nums [] int, target int) int {
// Replace this placeholder return statement with your code
return -1;
}
Binary Search