1

Binary Search

Unsolved
Search

Difficulty: 3 | Problem written by zeyad_omar
Problem reported in interviews at

Amazon
Apple
Facebook
Google
Netflix

Binary search is a searching algorithm that is very important and widely used in Computer Science.

Binary search is beautiful due to the fact that it is very fast compared to most searching techniques: complexity O(log(n)).

In this problem you are asked to implement binary search function given a 1D array and a target value.

Return the index of the target value, and if it is not found, return -1.

*Hint: Assume we are searching for the word "engineer" in the dictionary. At first, we open the middle of the dictionary. We find that it is in the "L" section so we know that our word is in the first half of the book. So we search in the middle of the first half. And so on...

**Note: Binary search only works when the input is sorted.

Sample Input:
<class 'list'>
x: [1, 2, 3, 4, 5]
target: 3

Expected Output:
<class 'int'>
2

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Nesciunt commodi enim adipisci illo eius doloremque ut sunt molestias repellendus. Quasi esse asperiores harum non velit eos nam quaerat beatae illo possimus? Consequuntur sunt repudiandae magni amet dolore rem tenetur debitis, adipisci quos itaque vel earum ipsam debitis, quia impedit repellat sint quas, nemo esse molestiae aut maxime libero ratione illo ipsum eos, doloribus laborum illo dicta soluta qui repudiandae temporibus facilis id. Consequuntur sapiente repudiandae, asperiores aperiam aspernatur porro fuga.

Quam mollitia iusto ipsum ad sapiente nisi incidunt, provident molestias necessitatibus impedit eum, quis eaque est asperiores. Enim laudantium laborum magni dicta accusantium deserunt reiciendis placeat, neque nostrum pariatur et?

Expedita dolore id sapiente aliquid recusandae officiis consectetur facere, dolor explicabo repellat sapiente repudiandae eos ullam quis nisi velit, quis a temporibus nihil sequi quos reprehenderit delectus blanditiis, obcaecati dignissimos autem inventore numquam commodi magnam voluptatibus vel veniam, quos numquam dolorum nemo voluptates consequuntur officiis accusantium?

This is a premium feature.
To access this and other such features, click on upgrade below.

Ready.

Input Test Case

Please enter only one test case at a time
numpy has been already imported as np (import numpy as np)