AW Dev Rethought

✂️ Perfection is achieved not when there is nothing more to add, but when there is nothing left to take away - Antoine de Saint-Exupéry

🧩 Python Algorithm Lab — Binary Search on the Answer 🐍


Description:

Binary search is not limited to finding values in sorted arrays. It can find the smallest answer that satisfies a condition—provided feasibility is monotonic.


The question

Ship packages with weights [3, 2, 2, 4, 1, 4] within at most three days. Keep the original order, do not split packages, and use the same capacity each day.

What is the minimum integer capacity?

  • Capacity 5: [3, 2] | [2] | [4, 1] | [4] → four days, so it fails.
  • Capacity 6: [3, 2] | [2, 4] | [1, 4] → three days, so it works.

Turn optimization into a yes/no question

Ask: “Can capacity C finish within the deadline?”

If a capacity works, every larger capacity works too: the same daily grouping still fits. The answers therefore form a boundary:

capacity:  4  5  6  7  8 ... 16
feasible:  F  F  T  T  T ...  T

We want the first true, not just any working capacity. If the predicate can switch back from true to false, this binary-search pattern does not apply.


Check one capacity greedily

def days_needed(weights, capacity):
    days, load = 1, 0
    for weight in weights:
        if weight > capacity:
            return float('inf')
        if load + weight > capacity:
            days += 1
            load = 0
        load += weight
    return days

For positive weights in fixed order, filling each day with the longest prefix that fits uses the fewest days. No alternative schedule can ship more items by the end of that first day; the same argument applies to the remaining packages.

Sorting the weights would change the problem. We never sort them.


Search the answer range

The lower bound is the heaviest package; the upper bound is the total weight, which fits everything in one day.

low, high = max(weights), sum(weights)
while low < high:
    mid = (low + high) // 2
    if days_needed(weights, mid) <= deadline:
        high = mid
    else:
        low = mid + 1
return low

The optimum stays inside [low, high], and high is feasible. A successful midpoint might be optimal, so retain it with high = mid. A failed midpoint rules out itself and every smaller capacity.

Bounds before check Midpoint Days Update
4–16 10 2 high = 10
4–10 7 3 high = 7
4–7 5 4 low = 6
6–7 6 3 high = 6

Both bounds meet at 6. Capacity 5 fails, confirming minimality.


Cost and verification

Each feasibility check scans n packages. For R = sum(weights) - max(weights) + 1 integer candidates, total runtime is O(n log(R + 1)), including bounds initialization. The basic search uses O(1) auxiliary space; the notebook’s optional trace uses O(log(R + 1)).

The implementation passed 2,004 comparisons against an independent oracle that enumerates every possible consecutive partition of small inputs. The notebook also checks invalid inputs. That exhaustive oracle is a testing tool, not the efficient algorithm.

The complete implementation validates nonempty positive integer weights and a positive integer deadline. No third-party packages are required.


Takeaway: build a correct monotonic feasibility check, choose valid bounds, and binary-search the first answer that works.


Link copied!

Comments

Add Your Comment

Comment Added!