15. Binary Search (1d array)

  • Lower & upper bound / search posn or insert into posn✅
  • floor & ceil✅
  • first & last occurrence of x          in sorted array✅
  • count occurrences of x                in sorted array✅
  • search    in rotated                         sorted array⭐✅
  • find min in rotated                         sorted array✅
  • count no. of times                       a sorted array         was rotated✅
  • find single elmt                          in sorted array⭐✅
  • peak element⭐⭐✅

------------------------------------------------------------------------------------------------------------

binary search works for sorted arrays ONLY.

it takes logN time for searching instead of linear time

binary search mein main thing is ye pehchanna ki kya eliminate krna hai

----------------------------------------------------------------------------------------------------------------------------

2 types of Binary Search:

iterative- (preferred)

remember to update the mid inside the loop


   












recursive-

in  BS, use, a+ (b-a)/2,   instead of (a+b)/2    to avoid overflow,

where a = low & b= high,  so a<=b always 

-----------------------------------------------------------------------------------------------------------------------------

Upper & Lower Bound-

used to find at what posn should a new number be inserted correctly in a sorted array....
-----------------------------

lower bound- first idx at which elmt present is >= x
upper bound- first idx at which elmt present is >x
-----------------------------

built-in:- this function returns the idx
-------------------------------

Lower bound- k se chote elmt in array jis index pe khatam hore uske just agle wala

                       - ceil in sorted array

                        - if no such lower bound exists then, ans is n (i.e., out of last idx n-1)

------------------------------

Upper bound

-------------------------------------------------------------------------------------------------------------
NOTE- 
ceil(x) is the value at lower bound of x, given that x is in the array
floor(x) can be computed using binary search. it isn't directly related to bounds
floor(x) is value at ( upper bound - 1 )


------------------------------------------------------------------------------------------------------------

First & last occurrence of x-
brute- O(n)
---------------------------------

optimal-    (time: 2logn)

lower bound(x) is the first occurrence of x   in a sorted array containing duplicates
upper bound(x)-1 is the last occurrence of x  ,,  ,,   ,,     ,,            ,,                  ,,

either, use built in fn 

or, implement yourself  


---------------------------------------------------------------------------------------------------------------

Search in Rotated sorted Array-(unique elmts)
binary lagake pehle mid pe dekho target hai ki nhi
fir dekho left ya right half konsa eliminate krna hai, by seeing konsa sorted hai and usme target bhi nhi hai...
har baar left ya right half mein se ek toh pkka sorted hoga hi hoga...


    
--------------------------------------------------------------------------------------------------------------
Search in Rotated sorted Array- (duplicate elmts)

only 1 edge case where, arr[low]==arr[mid]==arr[high]

-------------------------------------------------------------------------------------------------------------

Min in Rotated Sorted Array-

har baar sorted half ka min leleke nikaldo ans

e.g., 4 5 6 7 0 1 2
jaise left half agar sorted hai toh uska min elmt lelo ab right half m binary search lagake naya sorted half dekhlo aur min update krdo if needed and so on...

---------------------------------------------------------------------------------------------------------
count no. of times sorted array is rotated
ans = min elmt ka indx.
-----------------------------------------------------------------------------------------------------------
Single elmt in sorted array-

QUES- every element appears exactly twice except for one, find that elmt
ANS- if nums[i] is the ans then nums[i]!=nums[i-1] & nums[i+1]

3 edge cases-     single elmt,         ans at 0th idx,         ans at last idx

brute- linear search 
----------------------------------------------------------

optimal-    binary search ⭐⭐

observation- 
niche ke example se dekho ki 4 se pehle waale har jode ka pehla banda even idx pe tha aur 4 ke baad ke har jode ka pehla banda odd idx pe hai ab,
toh hum mid wale pe dekhenge ki ye mid idx odd hai ya even aur saath me ye konsi condn follow krra, us hisaab se fir right ya left mein ghumenge
above code says ki agar tu left half mein hoga desired elmt ke toh tera mid aisa hoga ki ya toh- mid even hoga aur uska agla elmt uske equal hoga YA mid odd hoga aur uska pichla elmt uske equal hoga, toh fir tu ab right half mein jaake dekh...
-------------------------------------------------------------------------------------------------------------

Peak Element-
find index of peak element , if there are many peaks return any
peak means strictly greater than nghbrs
--------------------------
edge cases- for first & last idx
-----------------------
brute- linear search

-----------------
Optimal- binary search

(I) For single peak element :-
1. there are 3 cases of mid (peak is left of mid,   mid=peak,  peak is on right of mid)
2. if element at mid!=peak 
    v[mid] > v[mid-1] then mid is on left increasing slope, so peak is on right, 
    v[mid] > v[mid+1] then mid is on right decreasing slope, so peak is on left...
(II) For multiple peaks :-

mostly cases would be covered by above code, except 1 edge case-
when (mid-1 > mid) && (mid+1>mid)
in such case, add an extra else condition where you can either go on the left or on the right as jaha abhi ho wahi toh ni hai peak uske agal bagal toh hai hi peaks

--------------------------------------------------------------------------------------------------------------
STEPS TO DO BINARY SEARCH-

1. pehle dekho ki simply sorted hai ya sorted ke baad thoda sa modified hai ki nhi
2. dekho ki hume optimise krna hai ki nhi

3. base cases likhlo
4. low and high decide kro
5. binary search ki condition socho observation se
--------------------------------------------------------------------------------------------------------------
NOTE-
1. hum iterative binary search krenge as per striver
2. hum vo wala binary search ni krenge use jisme low aur high ko modify krte hain

Comments

Popular posts from this blog

18. greedy algorithm

19. strings (LB)

17. BINARY SEARCH on 2d arrrays