Cutting Ribbons - Problem

Imagine you're a craft store owner with various ribbons of different lengths, and a customer needs k ribbons of identical length for a special project. Your job is to find the maximum possible length you can cut to satisfy their request!

Given an array ribbons where ribbons[i] represents the length of the i-th ribbon, and an integer k, you need to determine the maximum length x such that you can cut at least k ribbons each of length x.

Key Rules:

  • You can cut any ribbon into smaller pieces of positive integer lengths
  • You can discard leftover pieces from cuts
  • If it's impossible to get k ribbons of the same length, return 0

Example: With a ribbon of length 4, you could cut it into: one piece of length 4, or one of length 3 + one of length 1, or two pieces of length 2, etc.

Input & Output

example_1.py โ€” Basic Case
$ Input: ribbons = [9,7,5], k = 3
โ€บ Output: 5
๐Ÿ’ก Note: We can cut the ribbons into: ribbon 9 โ†’ one piece of length 5 (discard 4), ribbon 7 โ†’ one piece of length 5 (discard 2), ribbon 5 โ†’ one piece of length 5. Total: 3 pieces of length 5.
example_2.py โ€” Multiple Cuts Per Ribbon
$ Input: ribbons = [7,5,9], k = 4
โ€บ Output: 4
๐Ÿ’ก Note: We can cut: ribbon 7 โ†’ one piece of length 4, ribbon 5 โ†’ one piece of length 4, ribbon 9 โ†’ two pieces of length 4. Total: 4 pieces of length 4.
example_3.py โ€” Impossible Case
$ Input: ribbons = [5,7,9], k = 22
โ€บ Output: 0
๐Ÿ’ก Note: Even if we cut all ribbons into pieces of length 1, we get 5+7+9 = 21 pieces, which is less than 22. Therefore, it's impossible.

Constraints

  • 1 โ‰ค ribbons.length โ‰ค 105
  • 1 โ‰ค ribbons[i] โ‰ค 105
  • 1 โ‰ค k โ‰ค 109
  • All ribbon lengths are positive integers

Visualization

Tap to expand
Optimal Ribbon Cutting VisualizationOriginal Ribbon 1: Length 9Original Ribbon 2: Length 7Original Ribbon 3: Length 5Binary Search Process:Search range: [1, 9]Step 1: Try mid = 5555Cuts: 9รท5=1, 7รท5=1, 5รท5=1 โ†’ Total=3 โ‰ฅ 3 โœ“Step 2: Try mid = 7Cuts: 9รท7=1, 7รท7=1, 5รท7=0 โ†’ Total=2 < 3 โœ—Answer: 5 (maximum valid length)Final Result:Length 5Length 5Length 53 ribbons of length 5 (with some waste)
Understanding the Visualization
1
Identify the search space
The answer must be between 1 and the longest ribbon
2
Use binary search property
If length X works, all smaller lengths also work
3
Count efficiently
For each candidate length, count total pieces possible
4
Converge to optimum
Binary search finds the maximum valid length
Key Takeaway
๐ŸŽฏ Key Insight: Binary search works because of the monotonic property - if we can create k ribbons of length X, we can definitely create k ribbons of any length smaller than X!
Asked in
Google 45 Amazon 38 Meta 32 Microsoft 28
52.0K Views
Medium-High Frequency
~15 min Avg. Time
1.9K 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