Yandex

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

GraphsGraphs46

  1. 1Breadth-First Search in Graphs
  2. 2Depth-First Search in Graphs
  3. 3Number of Provinces in an Undirected Graph
  4. 4Connected Components in a Matrix
  5. 5Rotten Oranges Problem - BFS in Matrix
  6. 6Flood Fill Algorithm - Graph Based
  7. 7Detect Cycle in an Undirected Graph using DFS
  8. 8Detect Cycle in an Undirected Graph using BFS
  9. 9Distance of Nearest Cell Having 1 - Grid BFS
  10. 10Surrounded Regions in Matrix using Graph Traversal
  11. 11Number of Enclaves in Grid
  12. 12Word Ladder - Shortest Transformation using Graph
  13. 13Word Ladder II - All Shortest Transformation Sequences
  14. 14Number of Distinct Islands using DFS
  15. 15Check if a Graph is Bipartite using DFS
  16. 16Topological Sort Using DFS
  17. 17Topological Sort using Kahn's Algorithm
  18. 18Cycle Detection in Directed Graph using BFS
  19. 19Course Schedule - Task Ordering with Prerequisites
  20. 20Course Schedule 2 - Task Ordering Using Topological Sort
  21. 21Find Eventual Safe States in a Directed Graph
  22. 22Alien Dictionary Character Order
  23. 23Shortest Path in Undirected Graph with Unit Distance
  24. 24Shortest Path in DAG using Topological Sort
  25. 25Dijkstra's Algorithm Using Set - Shortest Path in Graph
  26. 26Dijkstra’s Algorithm Using Priority Queue
  27. 27Shortest Distance in a Binary Maze using BFS
  28. 28Path With Minimum Effort in Grid using Graphs
  29. 29Cheapest Flights Within K Stops - Graph Problem
  30. 30Number of Ways to Reach Destination in Shortest Time - Graph Problem
  31. 31Minimum Multiplications to Reach End - Graph BFS
  32. 32Bellman-Ford Algorithm for Shortest Paths
  33. 33Floyd Warshall Algorithm for All-Pairs Shortest Path
  34. 34Find the City With the Fewest Reachable Neighbours
  35. 35Minimum Spanning Tree in Graphs
  36. 36Prim's Algorithm for Minimum Spanning Tree
  37. 37Disjoint Set (Union-Find) with Union by Rank and Path Compression
  38. 38Kruskal's Algorithm - Minimum Spanning Tree
  39. 39Minimum Operations to Make Network Connected
  40. 40Most Stones Removed with Same Row or Column
  41. 41Accounts Merge Problem using Disjoint Set Union
  42. 42Number of Islands II - Online Queries using DSU
  43. 43Making a Large Island Using DSU
  44. 44Bridges in Graph using Tarjan's Algorithm
  45. 45Articulation Points in Graphs
  46. 46Strongly Connected Components using Kosaraju's Algorithm

TriesTries1

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:

  • Each student gets at least one book.
  • Each book is allocated to exactly one student.
  • Books allocated to a student must be in a contiguous block (i.e., no skipping).

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) Students Output Description
[10, 20, 30, 40] 2 60 Allocate [10, 20, 30] to one student and [40] to another → max pages = 60
[12, 34, 67, 90] 2 113 Best allocation: [12, 34, 67] and [90] → max = 113
[5, 17, 100, 11] 4 100 Each student gets one book → max = 100
[10, 20, 30, 40] 5 -1 More students than books → allocation not possible
[100] 1 100 Only one book and one student → give full book
[50, 60] 1 110 One student must take all books → total = 110
[] 1 -1 Empty book list → cannot allocate
[15, 25, 35] 0 -1 No 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.
Worst 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

You can support this website with a contribution of your choice.

When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M