15. Binary Search (1d array)
BINARY SEARCH-
1. works when search space is monotonic (e.g., sorted arrays)
(Binary search works on any structure that has a monotonic property)
2. Takes logN time
3. Identify what to eliminate
4. It should always happen on a range where we never touch invalid indices (khudse bounds ki tension na ho)
---------------------------------------------------------------------------------------------------------------
Decision tree to use binary search-
1. If search space is monotonic.
2. If we want to optimise O(n) solution
3. You can discard some possibilities by choosing some X at each step
-------------------------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------------------------
How to use binary search-
1. Define search space
1. Define search space
2. Define low and high
3. Identify binary search condition to eliminate search space
--------------------------------------------------------------------------------------------------------------
Iterative Binary Search-
below code finds index of a target number in an array
----------------------------------------------------------------------------------------------------------------------------
Recursive Binary Search-
---------------------------------------------------------------------------------------------------------------1. Upper & Lower Bound-
used to find, at what posn, should a new number be inserted correctly in a sorted array.
If no bound exists then, ans is n (size of array)------------------------------------------------------
Built-in function:
returns the idx
returns the idx
Lower bound:
1. x se chote elmt jis index pe khatam hore, uske just agle wala index.
2. first idx at which elmt present is >= x
---------------------------------------------------
Upper bound- first idx at which elmt present is >x
-------------------------------------------------------------------------------------------------------------
2. Ceil & Floor in Sorted array-
1. Ceil(x) :
value at lower bound(x)
smallest number in array, which is >=x
value at lower bound(x)
smallest number in array, which is >=x
-----------
2. Floor(x) :
value at: upper bound(x) - 1
largest number in array which is <= x
2. Floor(x) :
value at: upper bound(x) - 1
largest number in array which is <= x
------------------------------------------------------------------------------------------------------------
3. Find first & last occurrence of x:⭐
(in a sorted array)
(in a sorted array)
Brute- time: O(n)
use linear search
use linear search
---------------------------------
Optimal- time: O(logn)using lower & upper bound concept
start position = lower bound(x)
end position = upper bound(x) - 1
-------------------------------------------------------------------------------------------------------------
Optimal- time: O(logn)
every element appears exactly twice except for one, find that elmt
---------------------------------------------------------------------------------------------------------------
4. Search in Rotated sorted Array-1
(unique elements)
(unique elements)
Optimal- time: O(logn)
we will use, Binary search but only in sorted half
Every time, atleast one half of the array must be sorted⭐
e.g., 1234567 --> 4567 | 123
if mid is at pivot => each half is individually sorted
mid is before pivot => left half of mid is sorted
mid is after pivot => right half of mid is sorted
------------------
if mid is at pivot => each half is individually sorted
mid is before pivot => left half of mid is sorted
mid is after pivot => right half of mid is sorted
------------------
1. Use binary search & check if, v[mid]==target
2. Choose, sorted half thus eliminating unsorted half, out of left & right half.
3. Now in this sorted half, we can easily check if target lies in this range or not & thus move low & high pointers accordingly.
3. Now in this sorted half, we can easily check if target lies in this range or not & thus move low & high pointers accordingly.
----------------------
--------------------------------------------------------------------------------------------------------------
4. Search in Rotated sorted Array-2⭐
(duplicate elements)
only 1 edge case which is to be explicitly covered now is: arr[low]==arr[mid]==arr[high]
in such case, we trim the search space
Worst case: time= O(n), e.g., 1 1 1 1 1 here we everytime do left++ and right--
Worst case: time= O(n), e.g., 1 1 1 1 1 here we everytime do left++ and right--
other possible edge cases are already covered in the code
5. Min in Rotated Sorted Array-
Optimal- time: O(logn)
1. minimum of a rotated sorted array occurs at pivot element
2. also, we know that there exists atleast 1 sorted half around mid
3. Every time, we can safely take the boundary element of the sorted half as a candidate, and we must continue searching in the unsorted half, because the pivot (global minimum) can only exist where sorting breaks.
1. minimum of a rotated sorted array occurs at pivot element
2. also, we know that there exists atleast 1 sorted half around mid
3. Every time, we can safely take the boundary element of the sorted half as a candidate, and we must continue searching in the unsorted half, because the pivot (global minimum) can only exist where sorting breaks.
---------------------------------------------------------------------------------------------------------
6. Count no. of times sorted array is right rotated⭐
Optimal- time: O(logn)
no. of times a rotated sorted array was rotated = index of minimum element
since, each right rotation in a sorted array shifts minimum element to the right by 1 place.
1 2 3 4 5
1 2 3 4 5
5 1 2 3 4
4 5 1 2 3
-----------------------------------------------------------------------------------------------------------
6. Single elmt in sorted array-⭐⭐
every element appears exactly twice except for one, find that elmt
-------------------------------
Brute- time: O(n) space: O(1)
linear search
linear search
----------------------------------------------------------
Optimal- time: O(logn)
use binary search ⭐
use binary search ⭐
Observation-
1. In a perfect paired sorted array, the 1st occurrence of a pair is at even index and 2nd occurrence at odd index.
2. However, if there is a single element in it, then this gets inverted, after the single element, i.e., after the single element, the 1st occurrence of any pair happens at odd index.
3. So, we see, if mid is odd or even index & which condition is followed by pair at mid.
4. And thus eliminate search space.
Also, since we are dealing with mid-1 & mid+1 so since they can go out of bounds, so we explicitly handle edge cases where our answer maybe at v[0] or v[n-1] and thus we now define our range as : low=1 & high=n-2
2. However, if there is a single element in it, then this gets inverted, after the single element, i.e., after the single element, the 1st occurrence of any pair happens at odd index.
3. So, we see, if mid is odd or even index & which condition is followed by pair at mid.
4. And thus eliminate search space.
Also, since we are dealing with mid-1 & mid+1 so since they can go out of bounds, so we explicitly handle edge cases where our answer maybe at v[0] or v[n-1] and thus we now define our range as : low=1 & high=n-2
-------------------------------------------------------------------------------------------------------------
7. Peak Element-⭐
find index of peak element , if there are many peaks return any
peak means strictly greater than neighbours
--------------------------
edge cases- for first & last idx
-----------------------
Brute- time: O(n)
linear search
linear search
----------------------------------------------------
Optimal- time: O(logn)
binary search
binary search
There is always atleast 1 peak within [ low, high ]
Peak will be at the position where slope changes.
rising slope => nums[mid] < nums[mid+1] => peak is towards right.
falling slope => nums[mid-1] > nums[mid] => peak is in left
since we deal with mid-1 & mid+1 hence we explicitly handle corner cases first.
Peak will be at the position where slope changes.
rising slope => nums[mid] < nums[mid+1] => peak is towards right.
falling slope => nums[mid-1] > nums[mid] => peak is in left
since we deal with mid-1 & mid+1 hence we explicitly handle corner cases first.
--------------------------------------------------------------------------------------------------------------





Comments
Post a Comment