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?- A. 20 22
- B. 16 22
- C. 16 25
- 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
- Problem: Burst balloons; bursting balloon i earns left × a[i] × right with its current neighbours (1 beyond the ends). Maximise coins…
- Problem: Find the minimum number of intervals to remove so that the rest are non-overlapping – implemented with sort by START and keeping…
- Problem: Find the length of the longest valid (well-formed) parentheses substring. python def longestvalid(s): st, best = [-1], 0 for i…
- Problem: Return the number of provinces (connected components) from an adjacency matrix using DFS. java static int provinces(int[][] m) {…
- Problem: Find the town judge: trusted by everyone else and trusting nobody (−1 if none). python def judge(n, trust): score = [0] (n + 1)…
- Problem: Find the cheapest network latency to reach all nodes from node k (network delay = max shortest distance). python import heapq def…