BackmediumGreedyuncategorizedmedium

Kingdom Cargo Optimization Solution

Problem Statement

In the medieval kingdom of Everia, the royal logistics team needs to transport a certain number of crates of goods to the neighboring kingdom of Valtoria. The crates are of different sizes and weights, and the team has a certain number of carts with varying capacities to load them. The team wants to minimize the number of carts used to transport all the crates, as each cart requires a team of horses. Given the weights and sizes of the crates and the capacities of the carts, find the minimum number of carts required to transport all the crates.

Example 1
Input
[[1, 2], [3, 4], [5, 6]]
Output
2

Explanation: Step-by-step: with input [[1, 2], [3, 4], [5, 6]], we first sort the crates by their weights in descending order. Then, we iterate over the crates and try to fit each crate into an existing cart. If a crate cannot fit into any existing cart, we create a new cart. In this case, we can fit the first two crates into one cart and the third crate into another cart, resulting in a total of 2 carts.

Example 2
Input
[[10, 10], [10, 10], [10, 10]]
Output
3

Explanation: Step-by-step: with input [[10, 10], [10, 10], [10, 10]], we first sort the crates by their weights in descending order. Then, we iterate over the crates and try to fit each crate into an existing cart. Since each crate has the same weight and size, we need to create a new cart for each crate, resulting in a total of 3 carts.

Constraints

  • 1 <= nums.length <= 10^5
  • -10^9 <= nums[i] <= 10^9
Live Compiler1 Free Run Available
Loading Editor...
Test Cases & Output
Click "Run" to test your 1 free compile trial!

🚀 Practice this problem

Run code, get AI hints & track streak

Sign Up Free

Kingdom Cargo Optimization — Problem Statement & Solution Guide

GreedyMediumMixed
TimeO(n log n)
|
SpaceO(1)

Problem Description

In the medieval kingdom of Everia, the royal logistics team needs to transport a certain number of crates of goods to the neighboring kingdom of Valtoria. The crates are of different sizes and weights, and the team has a certain number of carts with varying capacities to load them. The team wants to minimize the number of carts used to transport all the crates, as each cart requires a team of horses. Given the weights and sizes of the crates and the capacities of the carts, find the minimum number of carts required to transport all the crates.

DSA Pattern Breakdown

DSA Pattern Breakdown

"Kingdom Cargo Optimization"

medium

WHY DOES IT MATTER?

The two‑pointer greedy pattern solves a wide class of resource‑allocation problems where items are interchangeable and the constraint is a single scalar limit. Mastery of this pattern lets engineers quickly turn seemingly combinatorial problems into linear scans, dramatically reducing runtime.

OPTIMIZATION CHALLENGE

The key insight is that after sorting, the heaviest remaining crate has only one viable partner that can possibly share a cart—the lightest crate that still fits. This eliminates the need to explore all pairings and collapses the search space to a single linear pass.

REAL-WORLD CONNECTION

Think of loading trucks at a distribution center: each truck has a weight ceiling, and you want to load the heaviest package with the lightest possible companion to maximize truck utilization—exactly what the algorithm does.

In an interview, sort first, then use two indices (low, high). Always test the sum of weights at low and high; if it exceeds capacity, ship the high alone. This simple loop is easy to code, debug, and explain.

COMPLEXITY AT A GLANCE

⏱ Time:O(n log n)
💾 Space:O(1)

Core Theory — Why This Approach?

The Kingdom Cargo Optimization problem is a classic instance of the two‑pointer greedy paradigm applied to a bounded‑capacity bin‑packing scenario. After sorting the crate weights, the lightest and heaviest remaining crates are examined: if they fit together within a cart’s capacity, they are paired and both are removed; otherwise the heaviest crate must travel alone. This greedy choice is provably optimal because any solution that does not pair the heaviest crate with the lightest possible partner would either waste a cart or force the heaviest crate to occupy a cart alone while a lighter crate could have been paired, contradicting minimality. Naïve enumeration of all subsets or recursive backtracking would explode exponentially (O(2^n) or worse) and cannot handle the typical input sizes (n up to 10^5). The optimal paradigm leverages sorting (O(n log n)) followed by a linear two‑pointer scan (O(n)), yielding an overall O(n log n) time solution with O(1) extra space.

Interview Questions on This Problem

Q1How would you modify the algorithm if each cart could hold up to three crates instead of two?

Sort the crate weights and use a three‑pointer approach: always try to fit the heaviest crate with the two lightest remaining ones. If the sum of the three fits, move all three pointers; otherwise, ship the heaviest alone and move only the high pointer. This greedy extension remains optimal because any optimal solution must place the heaviest crate somewhere, and pairing it with the lightest possible companions maximizes utilization.

Q2Explain why the two‑pointer greedy algorithm fails if the cart capacity can vary per cart.

When capacities differ, the decision of which crates to pair depends on the specific remaining capacities, breaking the exchange argument that guarantees optimality for a uniform limit. The greedy choice of pairing the lightest with the heaviest may leave a later cart with insufficient capacity for remaining crates, requiring a more complex matching or DP solution.

Q3What is the time‑space trade‑off if you need to output the exact assignment of crates to carts, not just the count?

You can still use the two‑pointer scan, but you must store each pairing in a list, which adds O(k) space where k is the number of carts (≤ n). The time remains O(n log n) for sorting plus O(n) for pairing, so overall O(n log n) time and O(n) auxiliary space for the assignment list.

Examples

Example 1

Input

[[1, 2], [3, 4], [5, 6]]

Output

2

Explanation: Step-by-step: with input [[1, 2], [3, 4], [5, 6]], we first sort the crates by their weights in descending order. Then, we iterate over the crates and try to fit each crate into an existing cart. If a crate cannot fit into any existing cart, we create a new cart. In this case, we can fit the first two crates into one cart and the third crate into another cart, resulting in a total of 2 carts.

Example 2

Input

[[10, 10], [10, 10], [10, 10]]

Output

3

Explanation: Step-by-step: with input [[10, 10], [10, 10], [10, 10]], we first sort the crates by their weights in descending order. Then, we iterate over the crates and try to fit each crate into an existing cart. Since each crate has the same weight and size, we need to create a new cart for each crate, resulting in a total of 3 carts.

Constraints

  • 1 <= nums.length <= 10^5
  • -10^9 <= nums[i] <= 10^9

Optimal Approach & Strategy

Sort the crates and apply a two‑pointer greedy scan, pairing the heaviest remaining crate with the lightest possible partner.

Brute Force Approach

Try every possible grouping of crates into carts, checking all subsets recursively to find the minimal cart count.

Verified Code Solutions

JavaScript Solution
Time: O(n log n)
function solution(crates, carts) { let cartsUsed = 0; let currentCartCapacity = 0; crates.sort((a, b) => b[1] - a[1]); for (let i = 0; i < crates.length; i++) { if (currentCartCapacity + crates[i][1] > carts[0][1]) { cartsUsed++; currentCartCapacity = 0; } currentCartCapacity += crates[i][1]; } if (currentCartCapacity > 0) { cartsUsed++; } return cartsUsed; }

Asked in Top Tech Interviews

uncategorizedmediumgeneric

Solve in Interative Editor

Ready to test your code? Open our built-in compiler, run custom test suites, and see detailed complexity analysis reports instantly.