Linear and Binary Search C++ Decode
Linear and Binary Search C++ Decode
Linear Searc
Binary searc
Practice questions
Linear Search
Overview: Linear Search, also known as Sequential Search, is a straightforward algorithm that sequentially
checks each element in a list until a match is found or the entire list has been searched.
Algorithm:
Continue this process until the end of the list is reached or the target is found.
Key Points:
Performance: Linear search has a time complexity of O(n) in the worst-case scenario, where 'n' is the number
Pseudocode in C++:
if (arr[i] == target) {
Example:
Note: While linear search is straightforward, it may not be efficient for large datasets or sorted lists.
Java
C++ &+ DSA
DSA
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 the middle element, the process is terminated
If the key is not found at the 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 the next search
If the key is larger than the middle element, then the right side is used for the next search
This process is continued until the key is found or the total search space is exhausted.
//Code
int l = 0, r = size - 1;
while (l <= r) {
int m = l + (r - l) / 2;
if (arr[m] == x)
return m;
if (arr[m] < x)
l = m + 1;
else
r = m - 1;
Java
C++ &+ DSA
DSA
// If we reach here, then element was not present
return -1;
Output: 4
Code:
Explanation: Simply use binary search as discussed above to find the target element
i e Complexity: O(logn) , because of binary search(each time we divide the array in half)
T m
Space: O(1)
Java
C++ &+ DSA
DSA
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
Code:
int mid;
high = mid;
} else {
low = mid + 1;
low++;
return low;
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.
C++, also has a build in builtin funciton to find lower bound using binary search lower_bound(arr.begin() ,
arr.end() , target
Q. Given a sorted integer array and an integer ‘x’, find the upper bound of x.
Input: 10 20 30 30 40 50
Java
C++ &+ DSA
DSA
//code
int mid;
int low = 0;
low = mid + 1;
} else {
high = mid;
if (low == size) {
cout << "The upper bound of " << key << " does not
exist." << endl;
return;
cout << "The upper bound of " << key << " is " << arr[low] <<
" at index " << low << endl;
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.
return x - array;
} else {
return -1;
Java
C++ &+ DSA
DSA
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
Output: 3
Output: 0
//code
int left = 0;
return mid;
if (arr[mid] == mid) {
left = mid + 1;
} else {
right = mid - 1;
return arr.size();
I t checks if the middle element matches its index and if the pre ious element is not missing (index wise)
v - .
I f the condition fails, the missing element is in the left half of the array otherwise, it s in the right half
; ' .
T he search continues in the respecti e half until the smallest missing number is found
v .
Java
C++ &+ DSA
DSA
Time Complexity: O(Log n) ,for binary search
Input: x = 4
Output: 2
//code
int floorSqrt(int x) {
// Base Cases
if (x == 0 || x == 1)
return x;
// If x is a perfect square
if (mid * mid == x)
return mid;
// sqrt(x)
start = mid + 1;
ans = mid;
end = mid - 1;
return 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).
Java
C++ &+ DSA
DSA
Run a loop until l <= r, the search space vanishes
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
arr.length >= 3
Given a mountain array arr, return the index i such that arr[0] < arr[1] < ... < arr[i - 1] < arr[i] > arr[i + 1] > ... >
arr[arr.length - 1].
Code:
int peakIndexInMountainArray(vector<int>& arr) {
int start = 0;
end = mid;
} else {
start = mid + 1;
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.
Java
C++ &+ DSA
DSA
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
` ` `
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;
half */
Java
C++ &+ DSA
DSA
return search(arr, mid + 1, h, key);
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).
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
int n = arr.size();
int L = R - 1;
while (k > 0) {
L--;
} else {
R++;
Java
C++ &+ DSA
DSA
}
k--;
vector<int> result;
result.push_back(arr[i]);
return result;
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
Output: true
Explanation: 1 * 1 + 2 * 2 = 5
Code:
class Solution {
public:
bool judgeSquareSum(int c) {
long l = 0, h = (long)sqrt(c);
while (l <= h) {
long cur = l * l + h * h;
if (cur < c) {
l++;
h--;
} else {
return true;
return false;
};
Java
C++ &+ DSA
DSA
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.
Time complexity: O(sqrt(c)log(c)), outer loop sqrt(c) , log(c) for binary search
Space: O(1)
Q. Median of Two Sorted Arrays (Leetcode 4)
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.size();
int m = B.size();
if (n > m)
int start = 0;
int end = n;
int realmidinmergedarray = (n + m + 1) / 2;
if ((m + n) % 2 == 0)
end = mid - 1;
} else {
start = mid + 1;
return 0.0;
Java
C++ &+ DSA
DSA
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
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:
int shipWithinDays(vector<int>& weights, int D) {
right += w;
need += 1;
cur = 0;
Java
C++ &+ DSA
DSA
cur += w;
if (need > D)
left = mid + 1;
else
right = mid;
return left;
Explanation:
Time Complexity: O(n * log n). We perform log n analyses, and for each we process n packages.
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:
Output: 30
Java
C++ &+ DSA
DSA
Code:
int time = 0;
if (time > h) {
int left = 1;
right = mid;
} else {
left = mid + 1;
return left;
Explanation: 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:
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
C++ &+ DSA
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.
Each bus can make multiple trips successively; that is, the next trip can start immediately after completing the
current trip. Also, each bus operates independently; that is, the trips of one bus do not influence the trips of any
other bus.
You are also given an integer totalTrips, which denotes the number of trips all buses should make in total.
Return the minimum time required for all buses to complete at least totalTrips trips.
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 5 trips is 3.
Code:
long sum = 0;
sum += x / t;
long lo = 1, hi = 100000000000000L;
lo = mid + 1;
} else {
hi = mid;
Java
C++ &+ DSA
DSA
}
return lo;
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
C++ &+ DSA
DSA
THANK
YOU !