AlgoTales · Roadmap

Book allocation

Advanced · 13 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

You have a row of items with sizes and must hand them in order to a fixed number of people so that the busiest person carries as little as possible. You guess a limit, check if it is enough with a simple walk, and halve the range of limits.

Practical use cases

  • Web app: Splitting exam papers among teachers. A college portal has 120 answer sheets in roll-number order with different page counts, and 5 teachers must each get a continuous block. The tool guesses a maximum pages per teacher and checks if 5 teachers are enough. In about 10 guesses it finds the fairest limit.
  • Web app: Dividing orders among packers. A warehouse dashboard splits a queue of orders, in arrival order, among 4 packers so that nobody has too much work. Guess a workload cap, assign orders in sequence until the cap is reached, and count the packers used. The best cap appears quickly.
  • System: Partitioning data across servers. When a long ordered log is split across several machines, engineers want the heaviest machine to be as light as possible. Dividing the work by effort rather than by row counts means no machine is still busy long after the others have stopped, so the whole job finishes sooner.

The story: Sharing the Holiday Homework Books

Mrs. Sharma had four books with 12, 34, 67 and 90 pages and two students to hand them to. The rules: every book goes to someone, each student gets books that sit next to each other on the shelf, and the student with the biggest load should have the lightest burden possible. "Be fair," she said.

Mira did not try every split. She guessed a limit: "What if nobody reads more than 100 pages?" Greedy check: give student 1 the books in order while they fit: 12, 34 (46 pages), and 67 would make 113, too many. So student 2 starts at 67; adding 90 gives 157, too many. Student 3 would be needed! But there are only 2 students. Limit 100 is too strict.

Try 120. Student 1: 12 + 34 + 67 = 113. Student 2: 90. Two students, fine! A bigger limit is always easier, a smaller one always harder. So the limits form a "no, no, no, yes, yes" line, and she halved it between 90 (the thickest book must be read by someone) and 203 (everything for one student). The first "yes" was 113. This is book allocation: guess the limit, check with a greedy split, halve.

How to spot this problem, and where you need it

You must split an ordered list of tasks or items into a given number of consecutive groups so that the biggest group total is as small as possible.

Signs you need it

  • The problem says "allocate books", "split array largest sum", "minimise the maximum load" or "k students".
  • Items must stay in order and each person gets a continuous block, not a random pick.
  • Trying every way to cut the list into k parts explodes in size.

Where to use it in a project

  • Task assignment screens that divide a queue among agents, teachers, packers or servers.
  • Batch jobs that split a big ordered file into equal-effort chunks.

The solution

The answer lies between the largest single item and the total of all items. Guess a cap in the middle. Walk through the items, giving each to the current person until adding the next would pass the cap, then start the next person. If you need no more than k people, the cap works, so try smaller; otherwise try larger. Repeat until the range closes.

Payoff: Before: checking every possible split of the list. After: about 20 guesses, each one pass over the items.

Explain it like I am 8

You and a friend must carry a line of bags home, each taking neighbouring bags, and you want to be fair. Say: "Nobody carries more than 100 kg!" Go along the line giving bags to the first person until they cannot take any more, then the second person. If you run out of people, 100 was too strict. Try a bigger limit.

How it works, step by step

  1. Range for the answer: at least the biggest book, at most the sum of all pages. (If there are more students than books, return -1.)
  2. Check a limit: go through the books in order, adding pages to the current student. If the next book would go over the limit, start a new student.
  3. Count the students you needed. If it is <= m, the limit works: high = mid. Otherwise the limit is too small: low = mid + 1.
  4. Repeat until low meets high.
  5. That number is the smallest possible largest load (minimise the maximum).

The code in four languages

PHP

<?php
// How many students are needed if nobody may read more than $limit pages?
function studentsNeeded(array $pages, int $limit): int {
    $students = 1;
    $current = 0;
    foreach ($pages as $p) {
        if ($current + $p > $limit) {
            $students++;               // this book would overload: next student
            $current = 0;
        }
        $current += $p;
    }
    return $students;
}

// Smallest possible "largest load" when splitting books among $m students.
function bookAllocation(array $pages, int $m): int {
    if ($m > count($pages)) return -1;       // someone would get no book
    $low = max($pages);                      // one student must read the biggest book
    $high = array_sum($pages);               // one student reads everything
    while ($low < $high) {
        $mid = intdiv($low + $high, 2);
        if (studentsNeeded($pages, $mid) <= $m) {
            $high = $mid;                    // limit is enough: try smaller
        } else {
            $low = $mid + 1;                 // too strict: allow more pages
        }
    }
    return $low;
}

echo bookAllocation([12, 34, 67, 90], 2), "\n";    // 113
echo bookAllocation([10, 20, 30, 40], 2), "\n";    // 60

JavaScript

// How many students are needed if nobody may read more than "limit" pages?
function studentsNeeded(pages, limit) {
  let students = 1;
  let current = 0;
  for (const p of pages) {
    if (current + p > limit) {
      students++;                        // this book would overload: next student
      current = 0;
    }
    current += p;
  }
  return students;
}

// Smallest possible "largest load" when splitting books among m students.
function bookAllocation(pages, m) {
  if (m > pages.length) return -1;       // someone would get no book
  let low = Math.max(...pages);          // one student must read the biggest book
  let high = pages.reduce((a, b) => a + b, 0);   // one student reads everything
  while (low < high) {
    const mid = Math.floor((low + high) / 2);
    if (studentsNeeded(pages, mid) <= m) {
      high = mid;                        // limit is enough: try smaller
    } else {
      low = mid + 1;                     // too strict: allow more pages
    }
  }
  return low;
}

console.log(bookAllocation([12, 34, 67, 90], 2));   // 113
console.log(bookAllocation([10, 20, 30, 40], 2));   // 60

Java

public class Main {
    // How many students are needed if nobody may read more than "limit" pages?
    static int studentsNeeded(int[] pages, int limit) {
        int students = 1;
        int current = 0;
        for (int p : pages) {
            if (current + p > limit) {
                students++;                    // this book would overload: next student
                current = 0;
            }
            current += p;
        }
        return students;
    }

    // Smallest possible "largest load" when splitting books among m students.
    static int bookAllocation(int[] pages, int m) {
        if (m > pages.length) return -1;       // someone would get no book
        int low = 0, high = 0;
        for (int p : pages) {
            low = Math.max(low, p);            // one student must read the biggest book
            high += p;                         // one student reads everything
        }
        while (low < high) {
            int mid = low + (high - low) / 2;
            if (studentsNeeded(pages, mid) <= m) {
                high = mid;                    // limit is enough: try smaller
            } else {
                low = mid + 1;                 // too strict: allow more pages
            }
        }
        return low;
    }

    public static void main(String[] args) {
        System.out.println(bookAllocation(new int[]{12, 34, 67, 90}, 2));   // 113
        System.out.println(bookAllocation(new int[]{10, 20, 30, 40}, 2));   // 60
    }
}

Go

package main

import "fmt"

// studentsNeeded: how many students are needed if nobody may read more than limit pages?
func studentsNeeded(pages []int, limit int) int {
	students := 1
	current := 0
	for _, p := range pages {
		if current+p > limit {
			students++ // this book would overload: next student
			current = 0
		}
		current += p
	}
	return students
}

// bookAllocation returns the smallest possible "largest load" when splitting books among m students.
func bookAllocation(pages []int, m int) int {
	if m > len(pages) {
		return -1 // someone would get no book
	}
	low, high := 0, 0
	for _, p := range pages {
		low = max(low, p) // one student must read the biggest book
		high += p         // one student reads everything
	}
	for low < high {
		mid := low + (high-low)/2
		if studentsNeeded(pages, mid) <= m {
			high = mid // limit is enough: try smaller
		} else {
			low = mid + 1 // too strict: allow more pages
		}
	}
	return low
}

func main() {
	fmt.Println(bookAllocation([]int{12, 34, 67, 90}, 2)) // 113
	fmt.Println(bookAllocation([]int{10, 20, 30, 40}, 2)) // 60
}

Time: O(n log S) · Extra space: O(1). S is the total number of pages. About log S guesses, and each check walks the n books once.

Watch out for

  • Starting low at 0 or 1. It must be at least the biggest book, or a single book would not fit.
  • Letting students read books that are not neighbours; the problem requires contiguous (side by side) books.
  • Forgetting the case with more students than books, where the answer is impossible.

Quick check

  1. What do we minimise?
    • The pages of the lightest student
    • The number of students
    • The pages of the heaviest student
  2. The limit needs MORE students than we have. What happens?
    • Limit is too small: low = mid + 1
    • Limit is fine: high = mid
    • Return -1
  3. Why is the smallest value of low the biggest single book?
    • Books can be torn
    • It is only a guess
    • Some student must read that book whole