Binary search obviously works on searching for elements in a sorted array. But if you think about the reason why it works is that the array itself is monotonic ( either increasing or decreasing ). So, if you are in a particular position, you can make a definite call whether the answer lies in the left part of the position or the right part of it.
A similar thing can be done with monotonic functions ( monotonically increasing or decreasing ) as well.
Let's say we have f(x)
which increases when x increases.
So, given a problem of finding x so that f(x) = p
, I can do a binary search for x.
In any instance,
1. if f(current_position) > p
, then I will search for values lower than current_position.
2. if f(current_position) < p
, then I will search for values higher than current_position
3. if f(current_position) = p
, then I have found my answer.
Problems for practice
SQRT
Problem | Score | Companies | Time | Status |
---|---|---|---|---|
Search in Bitonic Array! | 100 |
|
53:22 | |
Smaller or equal elements | 200 |
|
33:04 | |
WoodCutting Made Easy! | 200 |
|
59:06 | |
Matrix Search | 250 |
|
36:51 | |
Search for a Range | 250 |
|
42:02 | |
Sorted Insert Position | 250 |
|
25:03 |
Problem | Score | Companies | Time | Status |
---|---|---|---|---|
Capacity To Ship Packages Within B Days | 200 |
|
48:23 | |
Matrix Median | 225 |
|
77:24 | |
Square Root of Integer | 275 |
|
40:32 | |
Allocate Books | 350 |
|
68:01 | |
Painter's Partition Problem | 350 |
|
81:38 | |
Red Zone | 400 |
|
45:08 |
Problem | Score | Companies | Time | Status |
---|---|---|---|---|
Implement Power Function | 275 |
|
59:44 | |
Simple Queries | 300 |
|
67:38 |
Problem | Score | Companies | Time | Status |
---|---|---|---|---|
Median of Array | 325 |
|
87:06 | |
Rotated Sorted Array Search | 325 |
|
56:53 |