How To Approach The Binary Search Problems
How can we know, that a problem can be solve using Binary Search? ☹️
If a problem satisfies points which are mentioned below, then a problem can be solved using Binary Search.
So the points are :
- The answer of a problem is Integer ( because decimal numbers are very weird numbers 🤪 until there is no termination after some decimal place).
- The answer lies between any range of Integers.
- And there are many numbers between our range which are satisfying the conditions of our answer ( means that they also can be our answer ) but we want a particular one from these numbers.
- Most important Point: These numbers ( which I mentioned in point number 3rd ) must be continuous.
- Why continuous?
- Suppose our range of answer is [L, R], Mid = (L + R) / 2, and if we somehow check that Mid cannot be our answer then we will sure that our answer is either lies between [L, Mid-1] or [Mid+1, R] ( because the numbers which are satisfying the conditions of the answer are continuous, So these numbers lies in any one interval, not both ).
- Suppose if they are not continuous then how we can decide in which interval our answer lies🤔 ( Means we cannot choose one interval between any of ( [L, Mid-1], [Mid+1, R] ) these two because maybe there are several numbers which are satisfying the conditions of our answer and some of these numbers are lies in [L, Mid-1] and some in [Mid+1, R]. That's why we want continuous numbers🤓 ).
So let's solve a Problem👨🏻💻
John has n stalls that have fixed positions and c cows.
And he wants that the minimum distance between any two cows is as large as possible And he has to find the largest minimum distance.
Example:
number of stalls = 6 , cows = 3
and positions of stalls are 1, 2, 4, 5, 8, 9.
The possible ways to place 3 cows are
Positions The minimum distance between any two cows
- 1, 2, 4 1
- 1, 2, 5 1
- 1, 2, 8 1
- 1, 2, 9 1
- 1, 4, 5 1
- 1, 4, 8 3
- 1, 4, 9 3
- 1, 5, 8 3
- 1, 5, 9 4
- 2, 4, 5 2
- 2, 4, 8 2
- 2, 4, 9 2
- 4, 5, 8 1
- 4, 5, 9 1
- 5, 8, 9 1
So the answer is 4 for ( 1, 5, 9 ).
So let's see how we can come up with the thinking that this problem can be solved using Binary Search.
- Yes, our answer is Integer.
- Yes, our answer lies between the range [ 0 (i.e maybe all cow have the same position), N( maximum distance between any two stalls i.e 9 - 1 = 8) ].
- Yes, the numbers which are satisfying the conditions of our answer are continuous ( because if 3 is the number which satisfies the conditions and it may not be the largest then we will sure that now our answer is lies between [4, R] not in [L, 2] ).
Code of this Problem 👨🏻💻.
ReplyDeleteFantastic post.
Really enjoyed reading it and it held my attention all the way through! Keep it up.
Read my Latest Post
Thanks :)
DeleteVery Nice 👌👍👍👍😀 Bro thanx a lot.... And put some more questions regarding this .... Nice keep it up
ReplyDelete