KatInterview

Longest Uniform Cut Length from Rope Pieces

Heaps, Sorting & SearchAuto-graded · 23 test cases
MediumAuto-gradedHeaps, Sorting & Searchbinary-searchbinary-search-on-answermonotonic-predicate

Last updated

Find the largest integer length such that cutting every rope into pieces of that length yields at least k pieces; tests binary search over a monotonic answer space.

Longest Uniform Cut Length

A workshop has a list of ropes, where ropes[i] is the length of the i-th rope (a positive integer). You are also given a target count k.

You want to produce at least k pieces that all have exactly the same integer length L. Each rope can be cut into as many pieces of length L as fit, and whatever remains of that rope (shorter than L) is thrown away. Ropes cannot be tied together, so a piece always comes from a single rope.

Return the largest integer L >= 1 for which the ropes together provide at least k pieces of length L. If no such positive length exists (even L = 1 gives fewer than k pieces), return 0.

Function

Implement longest_uniform_cut(ropes, k), which takes the list of rope lengths and the integer k, and returns a single integer.

Constraints

  • 1 <= len(ropes) <= 10^5
  • 1 <= ropes[i] <= 10^9
  • 1 <= k <= 10^9
  • The result is an integer; return 0 when it is impossible to get k pieces of length at least 1.

Examples

Example 1

Input: longest_uniform_cut([5, 9, 7], 4)

Output: 4

Example 2

Input: longest_uniform_cut([5, 9, 7], 3)

Output: 5

Example 3

Input: longest_uniform_cut([2, 3], 10)

Output: 0

Hints

Hint 1

For a fixed length L, a rope of length w gives exactly w // L pieces. Summing this over all ropes tells you whether L works.

Hint 2

As L grows, the total number of pieces never increases. So the lengths that work form a prefix of 1, 2, 3, ... and you want the end of that prefix.

Hint 3

Binary search on L between 1 and max(ropes). Record L whenever it is feasible and then try larger; otherwise try smaller. If nothing is feasible, the answer stays 0.