Data Structures & AlgorithmsVery hardProduct Company SDE · Amazon/Microsoft-style OA

Problem: Find the cheapest way to cut a stick of length n at given positions; each cut costs the current piece's length.

Problem: Find the cheapest way to cut a stick of length n at given positions; each cut costs the current piece's length.
from functools import lru_cache
def cut(n, cuts):
    c = [0] + sorted(cuts) + [n]
    @lru_cache(None)
    def go(i, j):
        if j - i < 2: return 0
        return c[j] - c[i] + min(go(i, k) + go(k, j) for k in range(i + 1, j))
    return go(0, len(c) - 1)
print(cut(7, (1, 3, 4, 5)), cut(9, (5, 6, 1, 4, 2)))
What is printed?
  1. A. 20 22
  2. B. 16 22
  3. C. 16 25
  4. D. 15 22

Correct answer: B. 16 22

Interval DP over the sorted cut positions: cutting piece (i, j) costs its length plus the best split of the two halves. For length 7 cutting in order 3, 5, 1, 4 costs 7 + 4 + 3 + 2 = 16, while cutting in the given order 1, 3, 4, 5 costs 7 + 6 + 4 + 3 = 20. O(m³) for m cuts.

More Coding Interview Problems questions

Exams that ask this topic