Cutting Ribbons - Problem

You are given an integer array ribbons, where ribbons[i] represents the length of the i-th ribbon, and an integer k. You may cut any of the ribbons into any number of segments of positive integer lengths, or perform no cuts at all.

For example, if you have a ribbon of length 4, you can:

  • Keep the ribbon of length 4
  • Cut it into one ribbon of length 3 and one ribbon of length 1
  • Cut it into two ribbons of length 2
  • Cut it into one ribbon of length 2 and two ribbons of length 1
  • Cut it into four ribbons of length 1

Your task is to determine the maximum length of ribbon, x, that allows you to cut at least k ribbons, each of length x. You can discard any leftover ribbon from the cuts.

If it is impossible to cut k ribbons of the same length, return 0.

Input & Output

Example 1 — Basic Case
$ Input: ribbons = [9,7,5], k = 3
Output: 5
💡 Note: We can cut the ribbons as follows: 9÷5=1 piece, 7÷5=1 piece, 5÷5=1 piece. Total = 3 pieces of length 5.
Example 2 — Multiple Cuts Per Ribbon
$ Input: ribbons = [7,5,9], k = 4
Output: 4
💡 Note: Cut ribbons: 7÷4=1 piece, 5÷4=1 piece, 9÷4=2 pieces. Total = 4 pieces of length 4.
Example 3 — Impossible Case
$ Input: ribbons = [5,7,9], k = 22
Output: 0
💡 Note: Even cutting all ribbons into pieces of length 1 gives us only 5+7+9=21 pieces, which is less than 22.

Constraints

  • 1 ≤ ribbons.length ≤ 105
  • 1 ≤ ribbons[i] ≤ 105
  • 1 ≤ k ≤ 109

Visualization

Tap to expand
Cutting Ribbons - Binary Search Solution INPUT Ribbons Array Visualization Length: 9 Length: 7 Length: 5 scale ribbons = [9, 7, 5] k = 3 (need at least 3 pieces) Search Range: [1, 9] min=1, max=max(ribbons) Binary search for max length ALGORITHM STEPS 1 Binary Search Setup left=1, right=9 (max ribbon) 2 Try mid = 5 Count pieces of length 5 9/5 = 1 piece 7/5 = 1 piece 5/5 = 1 piece Total = 3 pieces (OK!) 3 Try mid = 7 9/7=1, 7/7=1, 5/7=0 Total=2 (not enough!) 4 Try mid = 6 9/6=1, 7/6=1, 5/6=0 Total=2 (not enough!) Max valid length = 5 FINAL RESULT Cutting with length x = 5 5 4 (waste) 5 2 5 (exact fit) Total pieces of length 5: 5 5 5 3 pieces (OK: 3 >= k) Output: 5 Maximum ribbon length = 5 Key Insight: Binary search on the answer! If we can cut k ribbons of length x, we might also achieve length x+1. For each candidate length, count total pieces: sum of floor(ribbon[i]/x). If count >= k, try larger length. Time Complexity: O(n * log(max_ribbon)) where n = number of ribbons. Space: O(1). TutorialsPoint - Cutting Ribbons | Binary Search Approach
Asked in
Google 25 Amazon 20 Meta 15
23.4K Views
Medium Frequency
~25 min Avg. Time
845 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen