Binery Search
Binery Search
Java
Binary Search
What & Why?
Binary search is an efficient algorithm used to search for a specific element within a sorted array or list. It works
by repeatedly dividing the search interval in half until the target element is found or the interval becomes
empty. Here's how it works:
Requirement: The array must be sorted in ascending or descending order for binary search to work effectively.
Algorithm:
In this algorithm,
Divide the search space into two halves by finding the middle index “mid”
Compare the middle element of the search space with the key.
If the key is found at middle element, the process is terminated
If the key is not found at middle element, choose which half will be used as the next search space
If the key is smaller than the middle element, then the left side is used for next search
If the key is larger than the middle element, then the right side is used for next search
This process is continued until the key is found or the total search space is exhausted.
Code:
int l = 0, r = arr.length - 1;
while (l <= r) {
int m = l + (r - l) / 2;
if (arr[m] == x)
return m;
if (arr[m] < x)
l = m + 1;
Java + DSA
// If x is smaller, ignore right half
else
r = m - 1;
// not present
return -1;
Given an array of integers nums which is sorted in ascending order, and an integer target, write a function to
search target in nums. If target exists, then return its index. Otherwise, return -1.
Output: 4
Java + DSA
Explanation: Simply use binary search as discussed above to find the target element
Time Complexity: O(logn) , because of binary search(each time we divide the array in half)
Space: O(1)
Q: Given a sorted integer array and an integer ‘x’, find the lower bound of x.
Input : 4 6 10 12 18 18 20 20 30 45
// ending index
int mid;
// left subarray
high = mid;
else {
low = mid + 1;
low++;
return low;
Java + DSA
Explanation: Initialize the low as 0 and high as N.
If the middle element is greater than or equal to the key then update the high as a middle index(mid).
After all the above steps the low is the lower_bound of a key in the given array.
Q: Given a sorted integer array and an integer ‘x’, find the upper bound of x.
Input : 10 20 30 30 40 50
Code:
{
// ending index
// right subarray
}
else {
high = mid;
}
Java + DSA
// If key is greater than last element which is
if (low == N ) {
return;
}
If the middle element is less than or equals to key then update the low as mid+1, Else update high as mid.
After all the above steps the low is the upper_bound of the key
Q: Given a sorted array of n elements and a target ‘x’. Find the first occurrence of ‘x’ in the array. If ‘x’ does
not exist return -1.
int x=lower_bound(array[],key)
if(array[x]==key) return x;
Explanation: Find the lower bound then check if the element at index lower bound equals the key the return the
index, else it means the element doesn’t exits
Time Complexity: O(logN),binary search,in lower_bound
Auxiliary Space: O(1), no extra space being used
Java + DSA
Q: Peak index in mountain array(leetcode 852)
arr.length >= 3
class Solution {
int start = 0;
end = mid;
} else {
start = mid + 1;
above
return start; }
Explanation:
Binary Search Approach: Helps find the maximum element in a rotated sorted array.
Comparing Midpoints: Check if the middle element is larger than its next element.
Deciding the Search Direction:
If it's larger, explore the left side for a potentially larger element
If not, explore the right side.
Refinement of Pointers:
start` and `end` pointers keep the best possible answer found so far
When they converge to one element, it's likely the maximum.
Java + DSA
Determining the Maximum: Return either `start` or `end` as they point to the maximum due to previous
comparisons.
There is an integer array nums sorted in ascending order (with distinct values).
Prior to being passed to your function, nums is possibly rotated at an unknown pivot index k (1 <= k <
nums.length) such that the resulting array is [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]]
(0-indexed). For example, [0,1,2,4,5,6,7] might be rotated at pivot index 3 and become [4,5,6,7,0,1,2].
Given the array nums after the possible rotation and an integer target, return the index of target if it is in nums,
or -1 if it is not in nums.
Code:
if (l > h)
return -1;
int mid = (l + h) / 2;
if (arr[mid] == key)
return mid;
in other half */
Java + DSA
/* If arr[l..mid] first subarray is not sorted,
Explanation: The idea is to create a recursive function to implement the binary search where the search region
is [l, r]. For each recursive call:
Based on that decide the next search region and keep on doing this till the element is found or l overcomes h.
Time Complexity: O(log N). Binary Search requires log n comparisons to find the element. So time complexity is
O(log n).
Auxiliary Space: O(1). As no extra space is required.
Given a sorted integer array arr, two integers k and x, return the k closest integers to x in the array. The result
should also be sorted in ascending order.
|a - x| < |b - x|, or
|a - x| == |b - x| and a < b
Output: [1,2,3,4]
Code:
import java.util.ArrayList;
import java.util.List;
int n = arr.length;
int L = R - 1;
Java + DSA
// Expand the [L, R] window till its size becomes
equal to k
while (k > 0) {
} else {
k--;
result.add(arr[i]);
return result;
int low = 0;
low = mid + 1;
} else {
high = mid;
return low;
int k = 4;
int x = 3;
List<Integer> closest =
solution.findClosestElements(arr, k, x);
Java + DSA
Explanation: We can take advantage of the fact that input array given to us is already sorted. We can use
binary search to find the smallest element in arr which is greater or equal to x. Let's mark this index as R. Let's
mark the index preceding to R as L and element at this index will be smaller than x.
Now, [L, R] forms our window of elements closest to x. We have to expand this window to fit k elements. We will
keep picking either arr[L] or arr[R] based on whichever's closer to x and expand our window till it contains k
elements.
Time Complexity : O(logn + k), We need O(logn) time complexity to find r at the start. Then we need another
O(k) time to expand our window to fit k elements
Space Complexity : O(1)
Given a non-negative integer c, decide whether there're two integers a and b such that a^2 + b^2 = c.
Input: c = 5
Output: true
Explanation: 1 * 1 + 2 * 2 = 5
Code:
class Solution {
long cur = l * l + h * h;
l++;
}
h--;
}
else
return true;
return false;
}
Explanation: Binary Search the given element in which up to the given number if the square number is greater
than the given number decrement the high and otherwise increment the low and in the else condition be true if
there are equal, otherwise return false.
Java + DSA
Time complexity : O(sqrt(c)log(c)), outer loop sqrt(c) , log(c) for binary search
Space : O(1)
Given two sorted arrays nums1 and nums2 of size m and n respectively, return the median of the two sorted
arrays.
Output: 2.00000
int n = A.length;
int m = B.length;
if (n > m)
return Median(B,
int start = 0;
int end = n;
int realmidinmergedarray = (n + m + 1) / 2;
int leftA
= (leftAsize > 0)
? A[leftAsize - 1]
: Integer
// of indices
: Integer.MIN_VALUE;
? A[leftAsize]
: Integer.MAX_VALUE;
? B[leftBsize]
: Integer.MAX_VALUE;
Java + DSA
// if correct partition is done
if ((m + n) % 2 == 0)
+ Math.min(rightA, rightB))
/ 2.0;
end = mid - 1;
else
start = mid + 1;
return 0.0;
Explanation: The given two arrays are sorted, so we can utilize the ability of Binary Search to divide the array
and find the median.
Median means the point at which the whole array is divided into two parts. Hence since the two arrays are not
merged so to get the median we require merging which is costly.
Hence instead of merging, we will use a modified binary search algorithm to efficiently find the median.
Time Complexity: O(min(log M, log N)): Since binary search is being applied on the smaller of the 2 arrays
Auxiliary Space: O(1),no extra space use
Q: Given a sorted array of non-negative distinct integers, find the smallest missing non-negative element in
it.
Input: {0, 1, 2, 6, 9}, n = 5, m = 10
Output: 3
Output: 0
Code:
int left = 0;
Java + DSA
// If the element at mid doesn't match its index
and the previous element is not missing
return mid;
if (arr[mid] == mid) {
left = mid + 1;
} else {
right = mid - 1;
return arr.length;
int smallestMissing =
solution.findSmallestMissing(arr);
It checks if the middle element matches its index and if the previous element is not missing (index-wise).
If the condition fails, the missing element is in the left half of the array; otherwise, it's in the right half.
The search continues in the respective half until the smallest missing number is found.
Given a non-negative integer x, return the square root of x rounded down to the nearest integer. The returned
integer should be non-negative as well.
Java + DSA
Input: x = 4
Output: 2
// Base Cases
if (x == 0 || x == 1)
return x;
// If x is a perfect square
if (mid * mid == x)
return (int)mid;
// sqrt(x)
start = mid + 1;
ans = mid;
end = mid - 1;
return (int)ans;
Explanation: The idea is to find the largest integer i whose square is less than or equal to the given number. The
values of i * i is monotonically increasing, so the problem can be solved using binary search.
Base cases for the given problem are when the given number is 0 or 1, then return X;
Create some variables, for storing the lower bound say l = 0, and for upper bound r = X / 2 (i.e, The floor of the
square root of x cannot be more than x/2 when x > 1).
Check if the square of mid (mid = (l + r)/2 ) is less than or equal to X, If yes then search for a larger value in the
second half of the search space, i.e l = mid + 1, update ans = mid
Else if the square of mid is more than X then search for a smaller value in the first half of the search space, i.e r =
mid – 1
Java + DSA
Time Complexity: O(log(X)), Binary search
Auxiliary Space: O(1), no extra space being used
Q: Capacity to ship packages within D days (leetcode 1011)
A conveyor belt has packages that must be shipped from one port to another within days days.
The ith package on the conveyor belt has a weight of weights[i]. Each day, we load the ship with packages on
the conveyor belt (in the order given by weights). We may not load more weight than the maximum weight
capacity of the ship.
Return the least weight capacity of the ship that will result in all the packages on the conveyor belt being
shipped within days days.
Output: 15
Explanation: A ship capacity of 15 is the minimum to ship all the packages in 5 days like this:
1st day: 1, 2, 3, 4, 5
2nd day: 6, 7
3rd day: 8
4th day: 9
5th day: 10
Note: That the cargo must be shipped in the order given, so using a ship of capacity 14 and splitting the
packages into parts like (2, 3, 4, 5), (1, 6, 7), (8), (9), (10) is not allowed.
Code:
right += w;
need += 1;
cur = 0;
cur += w;
return left;
Java + DSA
Explanation:
Time Complexity: O(n * log n). We perform log n analyses, and for each we process n packages.
Auxiliary Space: O(1), no extra space being used
Koko loves to eat bananas. There are n piles of bananas, the ith pile has piles[i] bananas. The guards have
gone and will come back in h hours.
Koko can decide her bananas-per-hour eating speed of k. Each hour, she chooses some pile of bananas and
eats k bananas from that pile. If the pile has less than k bananas, she eats all of them instead and will not eat
any more bananas during this hour.
Koko likes to eat slowly but still wants to finish eating all the bananas before the guards return.
Return the minimum integer k such that she can eat all the bananas within h hours.
Example 1:
Output: 4
Example 2:
Input: piles = [30,11,23,4,20], h = 5
Output: 30
Code:
class Solution {
int left = 1;
right = mid;
} else {
left = mid + 1;
Java + DSA
return left;
int time = 0;
if (time > h) {
Example 1:
Intuition
We need to find the minimum integer k such that Koko can eat all the bananas within h
hours. This means that we need to find the smallest value of k such that she can eat all
Approach
Initialize left and right pointers as left = 1 and right = maximum number of bananas in any pile.
While the left pointer is less than the right pointer, repeat the following:
a. Calculate the middle pointer using mid = (left + right) / 2.
b. Check if Koko can eat all the bananas at the current speed (middle pointer) within h hours using the
canEatAll method.
c. If Koko can eat all the bananas at the current speed, update the right pointer to the middle pointer using right
= mid.
d. If Koko cannot eat all the bananas at the current speed, update the left pointer to mid + 1.
Once the left pointer is equal to the right pointer, return the left pointer as the minimum speed at which Koko
can eat all the bananas within h hours.
The canEatAll method calculates the total time required to eat all the piles using the given speed. If the total
time is greater than h, the method returns false, otherwise, it
returns true.
Java + DSA
Time Complexity: O(n * log n).The binary search algorithm has a time complexity of O(logn), where n is the
maximum number of bananas in a pile. The canEatAll function has a time complexity of O(n), where n is the
number of piles We perform log n analyses, and for each we process n packages.
Eac us can ma e multiple trips successi ely t at is, t e next trip can start immediately a ter completin
h b k v ; h h f g
t e current trip Also, eac us operates independently t at is, t e trips o one us do not in luence t e trips
h . h b ; h h f b f h
o any ot er us
f h b .
Y ou are also i en an inte er totalTrips, ic denotes t e num er o trips all uses s ould ma e in total
g v g wh h h b f b h k .
R eturn t e minimum time re uired or all uses to complete at least totalTrips trips
h q f b .
Output: 3
Explanation:
At time t = 1, the number of trips completed by each bus are [1,0,0].
The total number of trips completed is 1 + 0 + 0 = 1.
At time t = 2, the number of trips completed by each bus are [2,1,0].
The total number of trips completed is 2 + 1 + 0 = 3.
At time t = 3, the number of trips completed by each bus are [3,1,1].
The total number of trips completed is 3 + 1 + 1 = . 5
So the minimum time needed for all buses to complete at least trips is 3. 5
Code:
long lo = 1, hi = 100000000000000L;
else hi = mid;
return lo;
long sum = 0;
Java + DSA
Explanation:
For any time x, we can have total trips = Σ(x / time[i]) where i in [0, time.size())
We need to minimize the above mentioned function total trips such that it is greater than or equal to the given
variable totalTrips.
On further inspection of the problem we can deduce that max value of x can be min(times) * totalTrips . So that
can be used as hi
Time Complexity: O(nlog(min(time) * totalTrips)) //n for the boolean f funciton // log(min(time)*totaltrips) for
binary search since max_x=min(time)*totaltrips
Java + DSA
THANK
YOU !