Binary TreesBinary Trees36

  1. 1Preorder Traversal of a Binary Tree using Recursion
  2. 2Preorder Traversal of a Binary Tree using Iteration
  3. 3Postorder Traversal of a Binary Tree Using Recursion
  4. 4Postorder Traversal of a Binary Tree using Iteration
  5. 5Level Order Traversal of a Binary Tree using Recursion
  6. 6Level Order Traversal of a Binary Tree using Iteration
  7. 7Reverse Level Order Traversal of a Binary Tree using Iteration
  8. 8Reverse Level Order Traversal of a Binary Tree using Recursion
  9. 9Find Height of a Binary Tree
  10. 10Find Diameter of a Binary Tree
  11. 11Find Mirror of a Binary Tree - Todo
  12. 12Inorder Traversal of a Binary Tree using Recursion
  13. 13Inorder Traversal of a Binary Tree using Iteration
  14. 14Left View of a Binary Tree
  15. 15Right View of a Binary Tree
  16. 16Top View of a Binary Tree
  17. 17Bottom View of a Binary Tree
  18. 18Zigzag Traversal of a Binary Tree
  19. 19Check if a Binary Tree is Balanced
  20. 20Diagonal Traversal of a Binary Tree
  21. 21Boundary Traversal of a Binary Tree
  22. 22Construct a Binary Tree from a String with Bracket Representation
  23. 23Convert a Binary Tree into a Doubly Linked List
  24. 24Convert a Binary Tree into a Sum Tree
  25. 25Find Minimum Swaps Required to Convert a Binary Tree into a BST
  26. 26Check if a Binary Tree is a Sum Tree
  27. 27Check if All Leaf Nodes are at the Same Level in a Binary Tree
  28. 28Lowest Common Ancestor (LCA) in a Binary Tree
  29. 29Solve the Tree Isomorphism Problem
  30. 30Check if a Binary Tree Contains Duplicate Subtrees of Size 2 or More
  31. 31Check if Two Binary Trees are Mirror Images
  32. 32Calculate the Sum of Nodes on the Longest Path from Root to Leaf in a Binary Tree
  33. 33Print All Paths in a Binary Tree with a Given Sum
  34. 34Find the Distance Between Two Nodes in a Binary Tree
  35. 35Find the kth Ancestor of a Node in a Binary Tree
  36. 36Find All Duplicate Subtrees in a Binary Tree

Allocate Minimum Pages to Students
Binary Search Optimization



Problem Statement

You are given a list of N books where each book has a certain number of pages, and you have to allocate these books to M students.

Your goal is to distribute the books among students in such a way that:

The task is to minimize the maximum number of pages assigned to a student across all students.

If it is not possible to allocate the books as per the rules, return -1.

Examples

Books (Pages)StudentsOutputDescription
[10, 20, 30, 40]260Allocate [10, 20, 30] to one student and [40] to another → max pages = 60
[12, 34, 67, 90]2113Best allocation: [12, 34, 67] and [90] → max = 113
[5, 17, 100, 11]4100Each student gets one book → max = 100
[10, 20, 30, 40]5-1More students than books → allocation not possible
[100]1100Only one book and one student → give full book
[50, 60]1110One student must take all books → total = 110
[]1-1Empty book list → cannot allocate
[15, 25, 35]0-1No students to allocate → invalid input

Solution

This problem is about fairly distributing work (in the form of book pages) among a group (students), such that no single person is overloaded compared to others.

The key constraint is that each student must receive a contiguous block of books. You cannot give a student book 1 and book 3 while skipping book 2.

Let's explore different scenarios to understand what the correct answer should look like:

  • Case 1: More students than books — This is not possible. Every student must get at least one book, and if books are fewer than students, we return -1.
  • Case 2: Equal number of students and books — This means each student will get exactly one book. The answer will be the maximum number of pages among the books because that’s the worst-case individual load.
  • Case 3: Only one student — The only student must read all the books. So the answer will be the total number of pages of all books.
  • Case 4: Normal case (fewer students than books) — This is where optimization is needed. We try different ways to divide books into blocks such that the student with the highest load has to read the least possible number of pages. This is done by exploring different values for the "maximum pages" and checking if the books can be divided accordingly.
  • Case 5: Empty book list — There's nothing to allocate, so we return -1.
  • Case 6: Zero students — No one is there to read the books. This is invalid input, so return -1.

The solution uses a smart way to search the answer using Binary Search instead of trying all combinations. It searches between the range max(arr) (because no student can be assigned fewer pages than the largest book) and sum(arr) (the case where one student gets everything). For each mid-value in this range, we check: is it possible to allocate books so that no student gets more than mid pages? If yes, we try to find a smaller answer. If not, we look for a higher value.

This process gives us the minimum possible value for the maximum pages a student has to read in a fair allocation.

Visualization

Algorithm Steps

  1. Set low = max(arr) and high = sum(arr).
  2. While low ≤ high, do:
  3. → Calculate mid = (low + high) / 2.
  4. → Check if it's possible to allocate books so that no student has more than mid pages using a helper function.
  5. → If possible, store the result and try to reduce it: high = mid - 1.
  6. → If not possible, increase the range: low = mid + 1.
  7. Return the minimum value found that satisfies the condition.

Code

Java
Python
JavaScript
C
C++
C#
Kotlin
Swift
Go
Php
public class BookAllocator {
  public static boolean isPossible(int[] arr, int m, int maxPages) {
    int students = 1;
    int pages = 0;
    for (int i = 0; i < arr.length; i++) {
      if (arr[i] > maxPages) return false;
      if (pages + arr[i] > maxPages) {
        students++;
        pages = arr[i];
      } else {
        pages += arr[i];
      }
    }
    return students <= m;
  }

  public static int findMinimumPages(int[] arr, int m) {
    if (m > arr.length) return -1;
    int low = arr[0], high = 0;
    for (int pages : arr) {
      low = Math.max(low, pages);
      high += pages;
    }

    int result = -1;
    while (low <= high) {
      int mid = low + (high - low) / 2;
      if (isPossible(arr, m, mid)) {
        result = mid;
        high = mid - 1;
      } else {
        low = mid + 1;
      }
    }
    return result;
  }

  public static void main(String[] args) {
    int[] arr = {12, 34, 67, 90};
    int students = 2;
    int minPages = findMinimumPages(arr, students);
    System.out.println("Minimum Maximum Pages: " + minPages);
  }
}

Time Complexity

CaseTime ComplexityExplanation
Best CaseO(n)Occurs if binary search hits the correct answer in the first try, but validation still needs to check all books.
Average CaseO(n * log(sum - max))Binary search over range from max(arr) to sum(arr), and for each guess, we iterate through n books.
Average CaseO(n * log(sum - max))Even in the worst case, we perform log iterations and n-time validation per iteration.

Space Complexity

O(1)

Explanation: Only a fixed number of variables are used. No extra space is needed.



Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

Mention your name, and programguru.org in the message. Your name shall be displayed in the sponsers list.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M