Table of contents
- 1. Solve the "allocate minimum number of pages" problem using binary search.
- 2. Solve the "minimum capacity required to ship packages within d days" problem.
- 3. Solve the "find the smallest missing positive integer" problem.
- 4. Solve the "number of times a sorted array is rotated" problem.
- 5. Solve the "median of two sorted arrays" problem using binary search.
Welcome to Day 14 of 100 Days of DSA challenge! Today, I solved five problems focused on binary search. Here's a quick look at the questions I tackled and how I approached them π€β¨ Check out my GitHub repository for all my solutions and progress. Letβs keep learning!
1. Solve the "allocate minimum number of pages" problem using binary search.
This problem can be solved using binary search by searching for the minimum possible maximum page load (capacity) that allows all books to be assigned to students. We set the range of binary search between the maximum number of pages in a book and the sum of all pages, then check at each step if it's feasible to allocate the books with the current capacity.
Code:
// Solve the "allocate minimum number of pages" problem using binary search.
#include<iostream>
using namespace std;
bool canAllocate(int arr[], int n, int m, int mid){
int studentCount = 1;
int currentSum = 0;
for(int i = 0; i < n; i++){
currentSum += arr[i];
if(currentSum > mid){
studentCount++;
currentSum = arr[i];
if(studentCount > m) return false;
}
}
return true;
}
int allocatePages(int arr[], int n, int m){
int sum = 0;
int maxPages = 0;
for(int i = 0; i < n; i++){
sum += arr[i];
maxPages = max(maxPages, arr[i]);
}
int low = maxPages, high = sum, result = -1;
while(low <= high){
int mid = (low + high) / 2;
if(canAllocate(arr, n, m, mid)){
result = mid;
high = mid - 1;
} else {
low = mid + 1;
}
}
return result;
}
int main(){
int arr[] = {12, 34, 67, 90};
int n = sizeof(arr) / sizeof(arr[0]);
int m = 2;
for(int i=0;i<8;i++){
cout<<arr[i]<<" ";
}
cout<<endl;
cout << "Minimum allocated pages:"<<allocatePages(arr, n, m) << endl;
return 0;
}
Output:
2. Solve the "minimum capacity required to ship packages within d days" problem.
To solve this, we perform binary search on the possible ship capacity. The lower bound of the search is the maximum weight of a package, and the upper bound is the sum of all package weights. At each step, we check if the current capacity allows the packages to be shipped in d
days, adjusting the bounds based on the feasibility.
Code:
#include<iostream>
using namespace std;
bool canShipCarry(int weights[], int size, int d, int capacity){
int days = 1;
int curr_weight = 0;
for(int i = 0; i < size; i++){
curr_weight += weights[i];
if(curr_weight > capacity){
days++;
curr_weight = weights[i];
if(days > d) return false;
}
}
return true;
}
int minDays(int weights[], int size, int d){
int low = 0, high = 0;
for(int i = 0; i < size; i++){
high += weights[i];
low = max(low, weights[i]);
}
while(low < high){
int mid = low + (high - low) / 2;
if(canShipCarry(weights, size, d, mid)){
high = mid;
} else {
low = mid + 1;
}
}
return low;
}
int main(){
int weights[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int d = 5;
int size = sizeof(weights) / sizeof(weights[0]);
int result = minDays(weights, size, d);
cout << "Minimum capacity required: " << result << endl;
return 0;
}
Output:
3. Solve the "find the smallest missing positive integer" problem.
This problem can be solved using binary search by first ensuring the array only contains positive integers and is sorted. We search for the first position where the value at the index is not equal to its index + 1, and that index gives the smallest missing integer.
Code:
// To find the smallest missing positive integer in an unsorted array
#include<iostream>
using namespace std;
int missingPositive(int arr[],int size){
int low=0;
int high=size-1;
while(low<=high){
int mid=(low+high)/2;
if(arr[mid]==mid+1){
low=mid+1;
}
else{
high=mid-1;
}
}
return low+1;
}
int main(){
int arr[4]={2,4,0,5};
for(int i=0;i<4;i++){
cout<<arr[i]<<" ";
}
cout<<endl;
int res=missingPositive(arr,4);
cout<<"The missing positive number is: "<<res;
}
Output:
4. Solve the "number of times a sorted array is rotated" problem.
The number of times a sorted array is rotated can be found using binary search by identifying the pivot point (the smallest element). We compare the middle element with the first and last elements to determine whether the pivot is in the left or right half, and adjust the search accordingly to find the rotation count.
Code:
// To find the number of times an array is rotated
#include<iostream>
using namespace std;
int noOfTimeArrayRotated(int arr[],int size){
int low=0;
int high=size-1;
while(low<=high){
if(arr[low]<=arr[high]){
return 0;
}
int mid=(low+high)/2;
// to make sure we dont go out of bounds
int prev=(mid-1+size)%size;
int next=(mid+1)%size;
if(arr[mid]<arr[prev] && arr[mid]<arr[next]){
return mid;
}
else if(arr[low]<=arr[mid]){
low=mid+1;
}
else{
high=mid-1;
}
}
}
int main(){
int arr[8]={4,5,6,7,8,1,2,3};
for(int i=0;i<8;i++){
cout<<arr[i]<<" ";
}
cout<<endl;
int res=noOfTimeArrayRotated(arr,8);
cout<<"Array has been roated for "<<res<<" steps";
}
Output:
5. Solve the "median of two sorted arrays" problem using binary search.
This problem can be solved by performing binary search on the smaller of the two arrays. By partitioning both arrays into two halves, we ensure that elements on the left are smaller than elements on the right. The median can then be found from the partitioned arrays by comparing boundary elements.
Code:
#include<iostream>
#include<vector>
using namespace std;
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
nums1.insert(nums1.end(), nums2.begin(), nums2.end());
sort(nums1.begin(), nums1.end());
int n = nums1.size();
if(n % 2 != 0) {
return nums1[n / 2];
} else {
return (nums1[n / 2 - 1] + nums1[n / 2]) / 2.0;
}
}
int main() {
vector<int> nums1 = {1, 3,4,5,6};
vector<int> nums2 = {2};
cout << "Median: " << findMedianSortedArrays(nums1, nums2) << endl;
return 0;
}
Output:
Happy Coding! πβ¨