Lecture 15: Book Allocation Problem || Aggressive Cows Problem || Binary Search Advanced Problems

Lecture 15: Book Allocation Problem || Aggressive Cows Problem || Binary Search Advanced Problems

Binary Search Problem Solving Series - Part 3

Introduction to Advanced Questions

  • The speaker, Love Babbar, introduces the final part of the binary search problem-solving series, focusing on advanced questions relevant for big tech companies like Google and Facebook.
  • Emphasizes that understanding core concepts will help in solving various question variations effectively.

Book Allocation Problem Overview

  • Introduces the "Book Allocation Problem," explaining it involves an array representing pages in books.
  • Clarifies that each element in the array corresponds to the number of pages in a book (e.g., [10, 20, 30, 40, 50]).

Conditions for Book Allocation

  • States there are 'm' students who need to be allocated books from the array.
  • Each student must receive at least one book and all books must be allocated without any left unassigned.
  • Highlights that allocation must be contiguous; students cannot receive non-adjacent books.

Objective of the Problem

  • The goal is to allocate books such that the maximum number of pages assigned to any student is minimized.
  • Acknowledges this may seem confusing initially but assures clarity through examples.

Example Walkthrough

  • Discusses a specific example with an array of values [10, 20, 30, 40] and 'm' set to 2 (two students).
  • Explains different allocation strategies:
  • First option: Student one gets 10 pages; student two gets remaining pages (90).
  • Second option: Student one receives up to 20 pages; student two gets remaining (70).
  • Third option: Student one receives three books totaling 60 pages; student two gets one book with 40 pages.

Calculating Maximum Pages Assigned

  • Details how to calculate total assigned pages for each strategy:
  • First case results in max = 90,
  • Second case results in max = 70,
  • Third case results in max = 60.

Finding Minimum Maximum Pages

  • Concludes by stating that since we need to minimize the maximum assigned pages across all allocations:
  • The minimum value among calculated maxima is determined as follows:
  • Max values were found as [90, 70, and 60].
  • Thus, minimum maximum assigned is concluded as 60.

Understanding Page Allocation to Students

Initial Setup and Case Analysis

  • The problem involves allocating books to two students, with a barrier indicating how many pages each student will read. The initial values are 10, 20, 30, and 40.
  • In the first case, the first student receives 10 pages while the second student reads the remaining 90 pages. The maximum number of pages read is thus 90.
  • For the second case, a barrier is set at 20; hence, the first student reads a total of 30 pages (10 + 20), while the second reads 70. The maximum here is now reduced to 70.
  • In the third case with a barrier at 30, allocations change again: the first student gets 60 pages and the second only gets 40. This results in a new maximum of just 60.
  • The goal is to find the minimum value among these maximum page counts across all cases; in this instance, it’s determined to be 60.

Binary Search Application

  • Although values like (10,20,30,40) are sorted for analysis purposes, sorting isn't strictly necessary for applying binary search techniques.
  • A previous lecture discussed using binary search to find square roots by minimizing search space; this concept will be applied similarly here.
  • To determine potential answers for book allocation based on constraints (at least two students and elements), we need to establish our search space limits.
  • The minimum possible answer starts logically from zero but isn’t feasible in practice; thus we consider it as part of our theoretical framework without complicating calculations unnecessarily.
  • Maximum possible value for allocation is calculated as the sum of all books (100), which also serves as an upper limit for our search space.

Midpoint Calculation and Feasibility Check

  • With established bounds from zero to one hundred for potential solutions, we calculate midpoints—starting with an initial midpoint of fifty.
  • We check if fifty can be allocated feasibly among two students: starting with ten pages for Student One remains under fifty; adding twenty keeps it under fifty too.
  • However, attempting to allocate thirty more exceeds fifty when combined with prior totals. Thus a barrier must be placed here before moving on to Student Two's allocation checks.

Adjusting Search Space Based on Results

  • Since Student Two cannot receive additional books without exceeding fifty due to barriers already established from earlier allocations—this indicates that fifty isn’t feasible given only two students available for distribution.
  • If fifty fails as a solution point due to insufficient capacity within constraints imposed by barriers then lower values should also not work since they would fall below this threshold.

Continuing Search Process

  • As such adjustments lead us back towards higher numbers—our next range becomes between fifty-one and one hundred after eliminating impossible options from previous checks.
  • Recalculating midpoints leads us next toward seventy-five where further feasibility checks begin anew regarding page distributions among both students.

Successful Allocation Example

  • At seventy-five: initial allocations remain valid until reaching forty where no further books can be distributed without exceeding limits set by prior sums—indicating successful partitioning has occurred within allowed parameters.
  • Since seventy-five proves viable as an allocation point any larger number must also hold true under similar conditions leading us toward identifying minimal thresholds effectively through iterative checking processes.

Conclusion on Minimum Value Discovery

Binary Search for Student Allocation

Understanding the Midpoint Calculation

  • The midpoint is calculated as mid = (51 + 74) / 2, resulting in mid = 62. This value will be used to check allocations.

Allocating Pages to Students

  • For the first student, possible allocations are 10, 20, or 30 pages; however, allocating 40 pages is not feasible. The partition point is established here.
  • After allocating pages to the first student, an attempt to allocate a total of 60 pages fails because it exceeds the current mid value of 56.

Adjusting Search Space

  • When reaching a third student with only two available, it indicates no solution exists for mid = 56. Thus, the search space shifts from [51,61] to [57,61].

Further Midpoint Calculations

  • A new midpoint calculation yields mid = (57 + 61) / 2 = 59. The allocation process continues with this updated mid value.

Finalizing Allocations and Solutions

  • With mid = 60, all students can be allocated their respective pages without exceeding limits. The final allocation confirms that all conditions are satisfied.

Implementing Binary Search Logic

Setting Up Variables for Code Implementation

  • Initialize variables: int s = 0; int sum = arr[i]; where sum represents the total number of pages across books.

Executing While Loop for Possible Solutions

  • Calculate mid using binary search logic: mid = s + (e - s)/2. This guides whether we can find a valid allocation within given constraints.

Storing Valid Solutions and Adjusting Search Space

  • If a valid solution exists at mid, store it in an answer variable (ans) and adjust search space by moving left (e = mid -1).

Handling Invalid Solutions

  • If no valid solution exists at mid, shift right by updating start (s = mid +1). Continue adjusting until a solution is found or confirmed impossible.

Defining Possible Solution Functionality

Counting Students and Page Sums

  • Create a function named isPossible(vector arr, int n, int m, int mid) which counts students while summing page allocations up to the current midpoint.

Evaluating Page Allocations Against Midpoint

  • As each page count is evaluated against the current midpoint (pageSum + arr[i] <= mid), adjustments are made based on whether adding another book exceeds this limit.

Managing Student Count and Conditions

Book Allocation Problem Explained

Understanding the Code Logic

  • The initial value of page sum starts at 0. Instead of using +=, it can be directly assigned to the array value, simplifying the code.
  • The solution checks if the current book count plus the previous sum is less than or equal to mid. If so, it adds; otherwise, it moves to the next student.
  • If all conditions are met, arr[i] is added to page sum, indicating successful allocation. All test cases passed successfully upon running.

Exploring Possible Solutions

  • A deeper explanation of checking for a possible solution involves evaluating whether a given mid-value (e.g., 56) can accommodate certain books without exceeding limits.
  • Starting with an initial page sum of 0, each book's pages are checked against mid. For example, adding 10 results in a valid page sum of 10 which is ≤ 56.

Handling Student Count and Page Sum

  • When attempting to add a new book (30), if it exceeds mid, a new student is created and page sums reset accordingly.
  • Before adding any book to page sums, it's crucial to check that its value does not exceed mid.

Final Walkthrough and Conditions for Success

  • The process involves starting from zero as minimum and finding maximum values through binary search while ensuring solutions exist within defined ranges.
  • Two main conditions for returning false: either exceeding student count (m) or individual book values surpassing mid.

Painter's Partition Problem Introduction

Problem Overview

  • The Painter's Partition Problem requires partitioning an array into sections that painters can handle continuously while minimizing total painting time.

Painter's Partition Problem and Aggressive Cows

Understanding the Painter's Partition Problem

  • The task involves partitioning boards to minimize total painting time, similar to allocating pages to students while minimizing the number of pages per student.
  • The search space for solutions is defined from 0 to the total sum (20), with a mid-point calculated at 10. This mid-point helps determine how many boards can be allotted to each painter.
  • By checking if the first painter can take certain boards based on their cumulative length compared to the mid-point, partitions are created effectively.
  • If a solution exists within a given range, that value is stored as a potential answer. The process continues by adjusting the search space based on whether more painters are needed or not.
  • When no solution is found (e.g., needing more painters than available), adjustments are made by moving forward in the search space until an optimal solution is identified.

Finalizing Solutions and Homework Assignment

  • Upon exhausting possible solutions without finding one, it’s concluded that previous calculations yielded an answer of 10, which was stored during earlier checks.
  • Viewers are encouraged to solve the Painter's Partition Problem as homework, reinforcing understanding of logic applied in this algorithmic challenge.

Introduction to Aggressive Cows Problem

Overview of Aggressive Cows Question

  • The next problem introduced is about assigning aggressive cows to stalls represented by an array of positions.
  • A key requirement is ensuring that cows are placed such that the minimum distance between any two cows is maximized, drawing parallels with previous allocation problems discussed.

Strategy and Search Space

  • The problem emphasizes understanding through examples; it highlights how visual cues in questions indicate strategies for solving them effectively.

Understanding the Largest Minimum Distance Problem

Introduction to the Problem

  • The task is to return the largest minimum distance by partitioning positions, focusing on maximizing the minimum distance between cows placed in stalls.
  • An example array of stall positions is given: 4, 2, 1, 3, 6. The problem involves placing K aggressive cows (e.g., C1 and C2) in these positions.

Placing Cows and Calculating Distances

  • The goal is to position the cows such that their minimum distance apart is maximized; understanding this requires visualizing placements along a line.
  • Various placements are explored:
  • C1 at position 4 and C2 at position 2 results in a distance of 2.
  • Other combinations yield distances of 3 (positions 4 and 1), and others continue to be calculated.

Finding Minimum Distances

  • By calculating all possible distances from different placements:
  • Examples include distances of 1 (between positions 2 and 1), up to a maximum of 5 (between positions 1 and 6).
  • All computed minimum distances are listed as: [2,3,1,2,1,1,4,2,5,3]. The largest among these is identified as the solution.

Verifying Solutions with Binary Search

  • To confirm findings for unsorted arrays like [4,2,1,3,6], binary search can be applied effectively.
  • If a certain distance (e.g., distance = 4) isn't feasible for cow placement due to aggression levels among them at that range.

Conditions for Applying Binary Search

  • If it’s impossible to place cows at one distance (like >4), then smaller distances must also be infeasible. This leads us toward using binary search logic.
  • Understanding whether solutions exist on either side of a midpoint allows for effective narrowing down through binary search principles.

Conclusion on Binary Search Application

Understanding Search Space in Binary Search

Defining the Search Space

  • The search space is determined by identifying the minimum and maximum values from the array, which is represented as mini and maxi. The example given is an array [4, 2, 1, 3, 6], where the minimum value starts at 0 and the maximum value is calculated as maxi - mini (e.g., 6 - 1 = 5) to establish a range of [0, 5].

Finding Midpoint for Cows Placement

  • The midpoint (mid) is calculated using (start + end) / 2. In this case, it results in a mid value of 2. A number line representation helps visualize cow placements. If cows are placed too close (distance less than mid), they cannot coexist peacefully. For instance, placing cows at positions 1 and 3 yields a distance of only 1, which fails to meet the required distance.

Evaluating Possible Solutions

  • The condition checked is whether two cows can be placed with a distance greater than or equal to mid (2). If successful (e.g., placing cows at positions that yield distances meeting or exceeding mid), it indicates a valid solution. This leads to storing the answer for further evaluation. The reasoning behind using "greater than or equal to" ensures that if cows do not fight at a certain distance, they will also not fight at larger distances.

Adjusting Search Space Based on Validity

  • Upon finding a valid placement solution (e.g., when both cows can be placed with sufficient distance), the algorithm shifts focus towards maximizing this distance by adjusting the search space rightward (start = mid + 1). This process continues until no further valid placements can be found within defined limits. Subsequent iterations refine potential solutions until reaching an endpoint where start equals end.

Finalizing Results through Iteration

Function of Possible Solution

Writing the Function

  • The function for solving the problem is crucial, as it encompasses all necessary elements. The initial cow count starts at 1, and the last position for placing cows is set to stalls.

Identifying Mistakes

  • A mistake was identified regarding the placement of cows on a number line; positions were not sorted correctly. Sorting is essential for proper placement.

Sorting Mechanism

  • The sorting process utilizes vector v.begin, which will be explained later. Understanding how to sort is fundamental to proceeding with cow placement.

Placing Cows in Stalls

Distance Check

  • When placing cows, if the distance between two positions (b - a) meets or exceeds a specified mid value, then placement is valid.

Looping Through Stalls

  • A loop iterates through stalls to check if arr[i] - last_position >= mid. If true, a cow can be placed.

Updating Cow Count

Incrementing Count

  • Upon successful placement of a cow, the cow count increments (cow_count++), and the last position updates to arr[i].

Validating Placement

  • If at any point cow_count == k, it indicates that all required cows have been placed successfully, leading to an immediate return of true.

Error Handling and Corrections

Debugging Issues

  • An error occurred due to incorrect vector declaration during sorting. Proper syntax must be followed when declaring vectors and using them in functions.

Binary Search Logic

Search Space Definition

  • The binary search logic involves defining start as 0 and end as the maximum number found. This helps determine possible placements efficiently.

Cow Placement Process

  • The first cow is placed at position 0; subsequent placements are checked against available stalls until all cows are positioned or deemed impossible.

Dynamic Programming Problems Overview

Problem Recap

  • Three dynamic programming problems were discussed: book allocation, painter partitioning, and aggressive cows. Each problem's approach was explained with homework assigned for coding practice.

Future Learning Directions

Upcoming Topics

  • Future lessons will cover recursive applications of binary search and fast exponentiation techniques. Engagement through comments will influence content frequency and topics covered in upcoming videos.

Conclusion & Next Steps

Anticipation for Next Video

Video description

In this Video, we are going to solve Binary Search Advanced questions. Questions Solved: - Book Allocation Problem - Painter’s Partition Problem - Aggressive Cows Problem There is a lot to learn, Keep in mind “ Mnn boot karega k chor yrr apne se nahi yoga ya maza nahi para, Just ask 1 question “ Why I started ? “ Visit Relevel: https://relvl.co/cu68 Discord Server Link: https://discord.gg/feSQvVXMrd Course Flow: https://whimsical.com/dsa-4-placement-by-love-babbar-C7JX2fJ8hprv9ivEHkArjD@2Ux7TurymNF9zkFahVLk Homework: Added in Video already Homework Questions: - Painter’s Partition Problem: https://bit.ly/31v3Jiy - EKO SPOJ: https://www.spoj.com/problems/EKO/ - PRATA SPOJ: https://bit.ly/3ExHXt5 Notes Link: https://drive.google.com/file/d/1d2eNEMdw5iuX7PflLfGykLgKF-SloUyr/view?usp=sharing Code Links: https://github.com/loveBabbar/CodeHelp-DSA-Busted-Series Question Links: - Book Allocation Problem: https://bit.ly/3GiCqY0 - Aggressive Cows: https://bit.ly/3dkuQ2B - Painter’s Partition Problem: https://bit.ly/31v3Jiy - EKO SPOJ: https://www.spoj.com/problems/EKO/ - PRATA SPOJ: https://bit.ly/3ExHXt5 Do provide you feedback in the comments, we are going to make it best collectively. Telegram Group Link: Love Babbar CODE HELP https://telegram.me/lovebabbercodehelp Connect with me here: Instagram: https://www.instagram.com/lovebabbar1/ Twitter: https://twitter.com/lovebabbar3 Intro Sequence: We have bought all the required Licenses of the Audio, Video & Animation used. Timestamps: 00:00 - Introduction 00:50 - Book Allocation Problem 04:28 - Promotion 05:37 - Approach 11:49 - Why Binary Search ? 24:29 - Code 31:49 - Dry Run 36:24 - Painter’s Partition Problem 43:24 - Homework 43:46 - Aggressive Cows Problem 49:30 - Why Binary Search ? 51:47 - Approach 57:36 - Code 01:04:10 - Homework #DSABusted #LoveBabbar