16. Binary Search on answers
How to identify if we can apply BSOA-
- answer is in an ordered search space within a defined min and max range
- we have a monotonic feasibility condition
- there is only 1 dimension as a constraint
- we have a monotonic feasibility condition
- there is only 1 dimension as a constraint
-------------------------------------------------------------------------------------------------------------
How to code BSOA-
1. identify search space for answer (min and max values)
2. identify monotonic quantity (which qty always inc or decrease as answer increases)
3. define a check(x) function using this quantity
4. binary search for a boundary, eliminating every time, either half.
1. identify search space for answer (min and max values)
2. identify monotonic quantity (which qty always inc or decrease as answer increases)
3. define a check(x) function using this quantity
4. binary search for a boundary, eliminating every time, either half.
--------------------------------------------------------------------------------------------------------------
1. Find Floor sqrt(n):
Brute- time: O(n)
using linear search to find largest i satisfying i*i = n
using linear search to find largest i satisfying i*i = n
--------------------------------------------------------------------
Better- time: O(logn)
f(x) = x*x is a monotonically increasing function. Hence,
we use binary search to find largest i satisfying i*i = n
low=1 and high=n
-----------------------------------------------------------------Better- time: O(logn)
f(x) = x*x is a monotonically increasing function. Hence,
we use binary search to find largest i satisfying i*i = n
low=1 and high=n
Optimal- time:(logn)
for n>=2,
sqrt(n) < n/2 [only for sqrt and not for nth root]
so we change our limits and now high = n/2
-------------------------------------------------------------------------------------------------------------
Note-
Note-
In built sqrt() function works in O(1) time since it is hardware instruction in CPU
----------------------------------------------------------------------------------------------------------------------------
to avoid overflow of mid^n, put a check : x^n > m => overflow => x is much larger value
----------------------------------------------------------------------------------------------------------------------------
2. Find Nth root of a number-
(if do not exist, then return -1)
to avoid overflow of mid^n, put a check : x^n > m => overflow => x is much larger value
---------------------------------------------------------------------------------------------------------------
find minimum days required to make B bouquets where a bouquet is made from k adjacent bloomed flowers.
max days = max time taken by a flower to bloom
min days = min time taken by a flower to bloom
find smallest divisor possible so that the sum we get after doing ceil(v[i]/divisor) is <= threshold.
------------------------------------------------------
Brute- time: O(N*M) where, M= max element
from 1 to max element we check for every number if it is possible , and return 1st possible divisor.
We will binary search on capacity with
min capacity = max weight of a load
max capacity = sum of all weights
Check function checks if a capacity x is able to ship all packages within d days.-----------------------------------------------------------------------------------------------------------------------------
Brute-
1. sort all the stall positions
2. Iterate through all possible minimum distances from 1 to max dist b/w any 2 cows.
3. For each min dist, see if we can arrange cows with a dist >= current min dist.
4. The largest possible min dist beyond which we can't arrange cows is our answer.
1. we find minimum no. of possible max pages allocated per student
here:
1. search space b/w: 0.0 (infinite stations to be added) & max_gap (no stations to be added)
2. monotonic quantity is max distance between 2 adjacent stations, as:
Brute- time: O(n+m) space: O(n+m)
Use two pointers to merge these two sorted arrays into a new array
and now if (n1+n2 = odd) => median at (n/2)th idx in new array
else, median = avg of elements at (n/2 -1)th idx & (n/2)th idx
here, we modify median of 2 sorted array problem
we intentionally, simulate such that overall left half has K elements
Now we do not care about right half
Kth element is max(L1, L2)
---------------------------------------------------------------------------------------------------------------
3. Koko eating bananas-
Koko can eat only from 1 pile per hour
-------------
Brute- time: O(NM)
we check for every possible speed from 1 to M(max bananas in a pile), that if it is a valid speed & cost to check a speed=x , is O(n) since we calculate: summation ceil(v[i]/x) <= h
--------------------
Optimal- time: O(NlogM)
Since, speed of eating bananas is monotonic
so we use binary search.
Speed is monotonic as:
if speed = x is valid, then all speed > x are also valid, so we look for a smaller speed
if speed = x is invalid, then it means it is very slow, hence all speed < x are also invalid.
check() function here checks if total hours (with speed=x) <= H
-------------
Brute- time: O(NM)
we check for every possible speed from 1 to M(max bananas in a pile), that if it is a valid speed & cost to check a speed=x , is O(n) since we calculate: summation ceil(v[i]/x) <= h
--------------------
Optimal- time: O(NlogM)
Since, speed of eating bananas is monotonic
so we use binary search.
Speed is monotonic as:
if speed = x is valid, then all speed > x are also valid, so we look for a smaller speed
if speed = x is invalid, then it means it is very slow, hence all speed < x are also invalid.
check() function here checks if total hours (with speed=x) <= H
4. Minimum days to make B bouquets-
find minimum days required to make B bouquets where a bouquet is made from k adjacent bloomed flowers.
----------------------
Brute- time: O(ND) , where D = max-min
Brute- time: O(ND) , where D = max-min
max days = max time taken by a flower to bloom
min days = min time taken by a flower to bloom
from min to max we check for every day if it is possible to make B bouquets
time to check if an answer is valid or not is: O(n)
Optimal- time: O(NlogD)
binary search on no. of days
check function here check if any possible no. of days = x, can make atleast b bouquets.
binary search on no. of days
check function here check if any possible no. of days = x, can make atleast b bouquets.
--------------------------------------------------------------------------------------------------------------
5. Smallest divisor for given threshold-
find smallest divisor possible so that the sum we get after doing ceil(v[i]/divisor) is <= threshold.
------------------------------------------------------
Brute- time: O(N*M) where, M= max element
from 1 to max element we check for every number if it is possible , and return 1st possible divisor.
--------------------------------------------------------
Optimal- time: O(N*logM)
instead of checking for every number we will binary search on them
and check feasibility for every mid
--------------------------------------------------------------------------------------------------------------
Optimal- time: O(N*logM)
instead of checking for every number we will binary search on them
and check feasibility for every mid
--------------------------------------------------------------------------------------------------------------
6. Minimum Capacity to ship packages in D days-
Brute- time: O(N*S)
we will check for every capacity from minimum to maximum possible capacity
we will check for every capacity from minimum to maximum possible capacity
& see which minimum capacity satisfies the conditions
------------------------------------------------
------------------------------------------------
Optimal- time ~ O(NlogS), where S is sum of all weights
We will binary search on capacity with
min capacity = max weight of a load
max capacity = sum of all weights
Check function checks if a capacity x is able to ship all packages within d days.
7. Kth Missing Number-⭐
Brute-
1. simulation based- time: O(answer) space: O(n)
1 se har number ko check karo ki vector mein hai ya nhi aur K missing numbers jab ho jaye toh Kth ko return kardo
----------------------------------------------------------------1 se har number ko check karo ki vector mein hai ya nhi aur K missing numbers jab ho jaye toh Kth ko return kardo
Better- time: O(n) space:O(1)
using Shifting k approach
Suppose you have empty array, therefore 5th missing number is 5
now suppose there is one element: 4, therefore, 5th missing number now is 6 (1,2,3,5,6)
if, array has one element: 7, then 5th missing number as: 5
now suppose there is one element: 4, therefore, 5th missing number now is 6 (1,2,3,5,6)
if, array has one element: 7, then 5th missing number as: 5
hence, do k++ for every v[i] <= k
else, break as bigger number do not affect K
---------------------------------------------------------------
Optimal- time: O(logn)⭐
Binary search on index
----------------------
LOGIC-
Monotonic function= count of missing numbers till index i => it always increases with i
First index with count>=k gives (ans = k + idx)
missing(mid) = arr[mid]-(mid+1) = no. of numbers missing till index 'mid'
if at index i (<k) missing numbers
Optimal- time: O(logn)⭐
Binary search on index
----------------------
LOGIC-
Monotonic function= count of missing numbers till index i => it always increases with i
First index with count>=k gives (ans = k + idx)
missing(mid) = arr[mid]-(mid+1) = no. of numbers missing till index 'mid'
if at index i (<k) missing numbers
if at index j (>k) missing numbers
then we know that after v[i] there are [ missing(j)-missing(i) ] missing numbers
and we only care about K-missing(i) itne more missing numbers after v[i]
so we add K-missing(i) to v[i] to get that Kth missing number
Hence, missing number = v[x-1] + K - [ v[x-1]- ((x-1)+1) ]
and we only care about K-missing(i) itne more missing numbers after v[i]
so we add K-missing(i) to v[i] to get that Kth missing number
Hence, missing number = v[x-1] + K - [ v[x-1]- ((x-1)+1) ]
= K+x
where, x is first index where no. of missing numbers >= k
where, x is first index where no. of missing numbers >= k
---------------------------------------------------------------------------------------------------------------------------
8. Aggressive Cows-
place such that min dist b/w cows is maximum
--------------------------------------------------------
Brute- time: O(NlogN + ND)
where D=distance between farthest and nearest stall to origin
where D=distance between farthest and nearest stall to origin
2. Iterate through all possible minimum distances from 1 to max dist b/w any 2 cows.
3. For each min dist, see if we can arrange cows with a dist >= current min dist.
4. The largest possible min dist beyond which we can't arrange cows is our answer.
-------------------------------------------------------
Optimal- time: O(NlogN + NlogD)
we binary search on minimum distances
9. Book Allocation Problem-⭐
1. we find minimum no. of possible max pages allocated per student
2. we check if max x no. of pages per student is possible for allocation or not.
3. we start searching for this minimum x from low to high range
4. lowest possible max page allocation per student = max pages in a book
highest possible max page allocation per student = he gets all books
----------------------------------------
Brute- time ~ O(NS)
where, S = total pages of all books
where, S = total pages of all books
Optimal- time: O(NlogS)
we binary search the minimum possible max pages allocation, instead of linear search.
monotonic function : f(x) = no. of students required if no student can get more than x pages.
as x increases => less students required => f(x) decreases.
as x decreases => more students required => f(x) increases.
for a valid x => look if some smaller x we can get
invalid x => look for greater x
invalid x => look for greater x
if, x no. of pages gives more number of students than required => x is small =>
x-1, x-2, ... will also give more students => we need larger x => invalid x
x-1, x-2, ... will also give more students => we need larger x => invalid x
if, x no. of pages gives less number of students required => x is large =>
x+1, x+2 , ... will give further lesser number of students => look for smaller x
x+1, x+2 , ... will give further lesser number of students => look for smaller x
---------------------------------------------------------------------------------------------------------------
10. Split array into K subarrays
(minimise the largest sum a subarray can have)
(minimise the largest sum a subarray can have)
the code and the logic is exactly same as of book allocation problem.
---------------------------------------------------------------------------------------------------------------
11. Painter partition problem-⭐⭐
1. Allot n walls to be painted by K painters
2. Each wall given to only 1 painter
3. painter paints only contigous segments of walls
3. painter paints only contigous segments of walls
4. no. of blocks to be painted in i-th wall is given by v[i]
5. minimise total time to paint the wall
5. minimise total time to paint the wall
6. Each painter takes t units of time to paint a block of wall.
-----------------------
-----------------------
Solution- same as that of book allocation problem.
1. create a new array with v[i] new = ( v[i] old * t )
1. create a new array with v[i] new = ( v[i] old * t )
2. now with this array we find minimum time to paint a wall
3. time to paint a wall is simply maximum time out of time taken by all painters
4. hence, problem reduces to finding min of max
3. time to paint a wall is simply maximum time out of time taken by all painters
4. hence, problem reduces to finding min of max
5. finding max of from k partitions from new array is similar to finding max from k partitions in old array, hence t is redundant in solving & we only consider it before returning ans.
-------------------------------------------------------------------------------------------------------------
12. Gas Stations-
(Floating point BSOA)
we will place K new gas stations b/w existing stations such that, we maintain equal distances b/w 2 consecutive stations.
-------------------------------------------------------------
Brute- time: O(N*k)
- Compute gaps between every pair of adjacent gas stations.
- Repeatedly (
ktimes) add a station to the gap whose current maximum segment length is largest. - Track how many stations are added to each original gap and recompute its effective segment length as :
gap / (added + 1). - After all insertions, the answer is the maximum segment length among all gaps
------------------------------------------------------------------------------------
Better- time: O(KlogN + nlogn) space: O(n)
OPTIMISATION-
instead of running a loop to find current max length of a section,
we will use a priority queue for finding max section length.
instead of running a loop to find current max length of a section,
we will use a priority queue for finding max section length.
---------------------------------------------------------------
Optimal- time: O(NlogP), where P=100 (precision)
Optimal- time: O(NlogP), where P=100 (precision)
in Floating point BSOA, just change these:-
1. take low & high in double instead of integers
2. instead of low<=high, do fixed number of iterations, since in floating numbers there is a possibility that low & high never cross each other & cause infinite loop
3. instead of high = mid-1 & low=mid+1 , here we do: low=mid & high=mid, since in floating numbers, +-1 leaves a lot of possible answers
1. take low & high in double instead of integers
2. instead of low<=high, do fixed number of iterations, since in floating numbers there is a possibility that low & high never cross each other & cause infinite loop
3. instead of high = mid-1 & low=mid+1 , here we do: low=mid & high=mid, since in floating numbers, +-1 leaves a lot of possible answers
(instead of iterations we can also do : while(high-low > 1e-6) ), if ques says return ans upto 6 decimal places
here:
1. search space b/w: 0.0 (infinite stations to be added) & max_gap (no stations to be added)
2. monotonic quantity is max distance between 2 adjacent stations, as:
- if gap is large => we need fewer stations
- if gap is small => we need more stations
3. if, (number of stations reqd with gap x) <= k : it means, gap is large so valid, so we can minimise it
-------------------------------------------------------------------------------------------------------------
13. Median of 2 sorted arrays-⭐
Brute- time: O(n+m) space: O(n+m)
Use two pointers to merge these two sorted arrays into a new array
and now if (n1+n2 = odd) => median at (n/2)th idx in new array
else, median = avg of elements at (n/2 -1)th idx & (n/2)th idx
--------------------------------------------
Better- time: O(n+m) space: O(1)
since we only care about two middle elements after merging
so instead of a vector we just use 2 variables and store in them the elements at (n/2 -1)th & n/2th positions.
since we only care about two middle elements after merging
so instead of a vector we just use 2 variables and store in them the elements at (n/2 -1)th & n/2th positions.
For this we use a counter which increase on every movement of a pointer.
Non Intuitive
(we are solving in log complexity only since question explicitly asks)
(we are solving in log complexity only since question explicitly asks)
using binary search.
----------
Logic:-
1. finding overall median is basically splitting all elements together into 2 partitions
2. both arrays contribute some elements to either of the partition
3. we binary search on smaller array that how many elements does it contribute to the overall left partition & we ourselves calculate, how many elements does the other array needs to contribute
4. now we just have to see if this partition is valid or not (by comparing cross elements at boundaries)
----------
Logic:-
1. finding overall median is basically splitting all elements together into 2 partitions
2. both arrays contribute some elements to either of the partition
3. we binary search on smaller array that how many elements does it contribute to the overall left partition & we ourselves calculate, how many elements does the other array needs to contribute
4. now we just have to see if this partition is valid or not (by comparing cross elements at boundaries)
5. if the partition is valid, we calculate median by seeing if n is odd or even and then finding (n/2)th and (n/2 -1)th element from the four border elements.
here we have put n/2 elements in left partition
hence in case of odd no. of elements in total
the median is in right half of total partition, hence max(right1, right2)
hence in case of odd no. of elements in total
the median is in right half of total partition, hence max(right1, right2)
---------------------------------------------------------------------------------------------------------------
14. K-th element of 2 sorted arrays-⭐
here, we modify median of 2 sorted array problem
we intentionally, simulate such that overall left half has K elements
Now we do not care about right half
Kth element is max(L1, L2)
see video :
high = min(k,n1)
low = max(0,k-n2)
low = max(0,k-n2)



Comments
Post a Comment