Tech Interview RoomStudy guides

Binary Search

Binary search on the answer: minimum ship capacity to deliver packages within D days.

Advanced · 2 min read · Lesson 3 of 3 in Binary Search

Problem

Package weights must be shipped in order; each day the ship carries a prefix of the remaining packages up to its capacity. Find the minimum capacity to finish within D days. weights = [1..10], D = 5 → 15.

Pattern

Binary search on the answer space: when "is capacity C enough?" is monotonic (if C works, any larger C works), binary search the smallest C that works between max(weights) and sum(weights), using a greedy O(n) feasibility check.

Approach 1: Try every capacity from the lower bound (feasible, O(n × range))

java
import java.util.Arrays;

class ShipLinear {
    static boolean canShip(int[] w, int cap, int days) {
        int used = 1, load = 0;
        for (int x : w) {
            if (load + x > cap) { used++; load = 0; }
            load += x;
        }
        return used <= days;
    }
    static int minCapacity(int[] w, int days) {
        int cap = Arrays.stream(w).max().orElse(0);
        while (!canShip(w, cap, days)) cap++;
        return cap;
    }
}

Approach 2: Binary search the capacity (O(n log(sum))) — optimal

java
import java.util.Arrays;

class ShipBinarySearch {
    static int minCapacity(int[] w, int days) {
        int lo = Arrays.stream(w).max().orElse(0);              // must carry the heaviest package
        int hi = Arrays.stream(w).sum();                         // everything in one day
        while (lo < hi) {
            int mid = lo + (hi - lo) / 2;
            if (ShipLinear.canShip(w, mid, days)) hi = mid; else lo = mid + 1;
        }
        return lo;
    }
}

class ShipDemo {
    public static void main(String[] args) {
        int[] w = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
        System.out.println(ShipLinear.minCapacity(w, 5) + " " + ShipBinarySearch.minCapacity(w, 5));   // 15 15
        System.out.println(ShipBinarySearch.minCapacity(new int[] {3, 2, 2, 4, 1, 4}, 3));             // 6
    }
}

Feasible → optimal

Scanning capacities is O(n × (sum − max)); binary search over the same range is O(n log(sum)). Recognise the pattern by the words "minimum value such that ..." or "maximum value such that ..." plus a monotonic check.

Follow-up questions interviewers ask

Try answering each one before you open it.

Related (same pattern): Koko eating bananas (minimum eating speed to finish within H hours).

Binary search speed in [1, max(pile)]; feasibility = sum(ceil(pile / speed)) <= H (compute ceil as (pile + speed - 1) / speed). O(n log max).

Related (same pattern): split an array into K subarrays minimising the largest sum.

Binary search the largest allowed sum in [max, total]; feasibility greedily counts how many subarrays are needed without exceeding it, the same check as the ship problem. O(n log(total)). Also used for "allocate books to students" and "painters partition".