KatInterview

Longest Equal Cable Segment From Spools

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

Last updated

Find the largest integer segment length such that cutting every spool into equal segments yields at least k segments, using binary search on a monotonic feasibility check.

A workshop has several spools of cable. The i-th spool has a length of spools[i] units, where every length is a positive integer. You need to cut segments that all have the same positive integer length L.

Rules for cutting:

  • Each spool is cut independently. A spool of length s yields s // L segments of length L (integer division). Any remainder is discarded.
  • Segments from different spools cannot be joined together.
  • You do not have to use every spool completely.

Given the list spools and an integer need, return the largest integer L >= 1 for which the total number of segments of length L across all spools is at least need.

If no positive integer length gives at least need segments (this happens exactly when the total length of all spools is less than need), return 0.

Constraints

  • 1 <= len(spools) <= 200000
  • 1 <= spools[i] <= 10^9
  • 1 <= need <= 10^12
  • The function returns a single integer.

Examples

Example 1

Input: longest_segment_length([9, 7, 5], 5)

Output: 3

Example 2

Input: longest_segment_length([5, 5, 5], 4)

Output: 2

Example 3

Input: longest_segment_length([1, 2, 3], 10)

Output: 0

Hints

Hint 1

For a fixed segment length L, how many segments can you get in total? Write it as a sum over the spools.

Hint 2

As L grows, the total number of segments never increases. What does that tell you about the set of feasible values of L?

Hint 3

Binary search L between 1 and the longest spool. Record the answer whenever a candidate is feasible, and move right; otherwise move left. If nothing is feasible, the answer stays 0.