Cutting Ribbons
Cutting Ribbons is a medium binary search problem solved with the binary search on answer space pattern.
The best approach, optimal (binary search on the length), runs in O(n log m) time and O(1) space.
Below are 2 approaches in Java, Python, C++ and JavaScript, from brute force (try every length from the top) up.
Problem
You have several ribbons, and ribbons[i] is the length of the i-th one. You also get an integer k.
You may cut any ribbon into pieces of whole-number lengths, as many times as you like, and you may throw away whatever is left over. Your goal is to end up with at least k pieces that all have the same length x.
Return the largest positive integer x for which this is possible. If no positive length gives k pieces, return 0.
Examples
Example 1
- Input
ribbons = [9,7,5], k = 3- Output
5- Why
- With length 5, each ribbon gives one piece: three pieces in total. Length 6 gives only two pieces (one from 9, one from 7, none from 5), so 5 is the largest length that works.
Example 2
- Input
ribbons = [10,4,6], k = 5- Output
3- Why
- Length 3 gives 3 + 1 + 2 = 6 pieces, which is enough. Length 4 gives 2 + 1 + 1 = 4 pieces, one short of 5.
Example 3
- Input
ribbons = [2,3], k = 7- Output
0- Why
- Even pieces of length 1 give only 2 + 3 = 5 pieces, fewer than 7, so no positive length works.
Constraints
1 <= ribbons.length <= 10^51 <= ribbons[i] <= 10^51 <= k <= 10^9
Solve it here
Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.
Your own testcases: Run checks these, and the expected output comes from our reference solution.
My submissions
Nothing yet. Every Run and Submit you make while signed in shows up here.
| When | Result | Tests | Runtime | Your time | Type |
|---|
Run checks the testcases above (3 examples, or your own). Submit also runs 14 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.
Animated walkthrough
A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
Solutions
Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.
| Approach | Time | Space |
|---|---|---|
| Brute force (try every length from the top) | O(n · m) | O(1) |
| Optimal (binary search on the length) | O(n log m) | O(1) |
1Brute force (try every length from the top)
O(n · m)Up to m lengths are tried, where m is the longest ribbon, and each try counts pieces over all n ribbons.O(1)Only a few counters.The answer can never be longer than the longest ribbon. Try every length x from the longest ribbon down to 1, count the pieces each one gives, and return the first x whose count reaches k. If none does, return 0.
- Find max, the longest ribbon.
- For x from max down to 1: pieces = sum of r / x over all ribbons (in a long).
- If pieces >= k, return x. Going from the top, the first success is the largest.
- If the loop ends, return 0.
class Solution {
public int maxLength(int[] ribbons, int k) {
int max = 0;
for (int r : ribbons) max = Math.max(max, r);
for (int x = max; x >= 1; x--) {
long pieces = 0;
for (int r : ribbons) pieces += r / x;
if (pieces >= k) return x;
}
return 0;
}
}class Solution:
def maxLength(self, ribbons: List[int], k: int) -> int:
for x in range(max(ribbons), 0, -1):
pieces = 0
for r in ribbons:
pieces += r // x
if pieces >= k:
return x
return 0class Solution {
public:
int maxLength(vector<int>& ribbons, int k) {
int mx = 0;
for (int r : ribbons) mx = max(mx, r);
for (int x = mx; x >= 1; x--) {
long long pieces = 0;
for (int r : ribbons) pieces += r / x;
if (pieces >= k) return x;
}
return 0;
}
};function maxLength(ribbons, k) {
let max = 0;
for (const r of ribbons) max = Math.max(max, r);
for (let x = max; x >= 1; x--) {
let pieces = 0;
for (const r of ribbons) pieces += Math.floor(r / x);
if (pieces >= k) return x;
}
return 0;
}2Optimal (binary search on the length)
O(n log m)The search range 0..m halves each round, so there are about log m rounds, each counting pieces over n ribbons.O(1)Only the bounds and the counter.The piece count can only go down as the length grows: a longer piece never fits more times into a ribbon. So the lengths that work are exactly 1, 2, up to some answer, and every longer length fails. Binary search for that boundary. Keep lo as a length known to work (start at 0, which stands for 'no length') and hi as the largest length that might work (the longest ribbon). Test mid: if it gives at least k pieces, the answer is at least mid; otherwise it is below mid.
- lo = 0, hi = the longest ribbon.
- While lo < hi: mid = lo + (hi - lo + 1) / 2, rounding up so the range always shrinks.
- Count pieces = sum of r / mid in a long. If pieces >= k, set lo = mid; otherwise set hi = mid - 1.
- When lo == hi, return lo. It is 0 when no positive length works.
class Solution {
public int maxLength(int[] ribbons, int k) {
int lo = 0, hi = 0;
for (int r : ribbons) hi = Math.max(hi, r);
while (lo < hi) {
int mid = lo + (hi - lo + 1) / 2;
if (pieces(ribbons, mid) >= k) lo = mid;
else hi = mid - 1;
}
return lo;
}
private long pieces(int[] ribbons, int x) {
long total = 0;
for (int r : ribbons) total += r / x;
return total;
}
}class Solution:
def maxLength(self, ribbons: List[int], k: int) -> int:
lo, hi = 0, max(ribbons)
while lo < hi:
mid = lo + (hi - lo + 1) // 2
if self.pieces(ribbons, mid) >= k:
lo = mid
else:
hi = mid - 1
return lo
def pieces(self, ribbons: List[int], x: int) -> int:
total = 0
for r in ribbons:
total += r // x
return totalclass Solution {
public:
int maxLength(vector<int>& ribbons, int k) {
int lo = 0, hi = 0;
for (int r : ribbons) hi = max(hi, r);
while (lo < hi) {
int mid = lo + (hi - lo + 1) / 2;
if (pieces(ribbons, mid) >= k) lo = mid;
else hi = mid - 1;
}
return lo;
}
private:
long long pieces(vector<int>& ribbons, int x) {
long long total = 0;
for (int r : ribbons) total += r / x;
return total;
}
};function maxLength(ribbons, k) {
let lo = 0, hi = 0;
for (const r of ribbons) hi = Math.max(hi, r);
while (lo < hi) {
const mid = lo + Math.floor((hi - lo + 1) / 2);
if (pieces(ribbons, mid) >= k) lo = mid;
else hi = mid - 1;
}
return lo;
}
function pieces(ribbons, x) {
let total = 0;
for (const r of ribbons) total += Math.floor(r / x);
return total;
}Edge cases to test
- The total length is less than k, so even length 1 fails (answer 0)
- k = 1: the answer is the longest ribbon
- The total length equals k exactly (answer 1)
- A single ribbon
- The piece count overflows a 32-bit int when many long ribbons are cut into length 1: count in a long
- Leftover bits of ribbon are thrown away, so a length can fail even if the total length is big enough
Hints
Hint 1
For a fixed length x, the number of pieces is the sum of ribbons[i] / x, rounded down. You can compute it in one pass.
Hint 2
If length x works, does every shorter length also work? What does that say about the set of lengths that work?
Hint 3
The lengths that work form a prefix 1..answer. Binary search the largest x in 1..max(ribbons) whose piece count reaches k.
FAQ
What is the best time complexity for Cutting Ribbons?
Optimal (binary search on the length) runs in O(n log m) time and O(1) extra space. The search range 0..m halves each round, so there are about log m rounds, each counting pieces over n ribbons.
Which pattern does Cutting Ribbons use?
It is a binary search problem that uses the binary search on answer space pattern. Other problems with the same pattern: Koko Eating Bananas, Minimum Number of Days to Make m Bouquets, Separate Squares I.
Is there a brute force solution for Cutting Ribbons?
Yes. Brute force (try every length from the top) takes O(n · m) time and O(1) space. The answer can never be longer than the longest ribbon.
Which edge cases should I test for Cutting Ribbons?
The total length is less than k, so even length 1 fails (answer 0); k = 1: the answer is the longest ribbon; The total length equals k exactly (answer 1); A single ribbon; The piece count overflows a 32-bit int when many long ribbons are cut into length 1: count in a long; Leftover bits of ribbon are thrown away, so a length can fail even if the total length is big enough.