Stealth Interview
  • Features
  • Pricing
  • Blog
  • Login
  • Sign up

Leetcode #1547: Minimum Cost to Cut a Stick

In this guide, we solve Leetcode #1547 Minimum Cost to Cut a Stick in Python and focus on the core idea that makes the solution efficient.

You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Leetcode

Problem Statement

Given a wooden stick of length n units. The stick is labelled from 0 to n.

Quick Facts

  • Difficulty: Hard
  • Premium: No
  • Tags: Array, Dynamic Programming, Sorting

Intuition

The problem breaks into overlapping subproblems, so caching results prevents exponential repetition.

A carefully chosen DP state captures exactly what we need to build the final answer.

Approach

Define the DP state and recurrence, then compute states in the correct order.

Optionally compress space once the recurrence is clear.

Steps:

  • Choose a DP state definition.
  • Write the recurrence and base cases.
  • Compute states in the correct order.

Example

Input: n = 7, cuts = [1,3,4,5] Output: 16 Explanation: Using cuts order = [1, 3, 4, 5] as in the input leads to the following scenario: The first cut is done to a rod of length 7 so the cost is 7. The second cut is done to a rod of length 6 (i.e. the second part of the first cut), the third is done to a rod of length 4 and the last cut is to a rod of length 3. The total cost is 7 + 6 + 4 + 3 = 20. Rearranging the cuts to be [3, 5, 1, 4] for example will lead to a scenario with total cost = 16 (as shown in the example photo 7 + 4 + 3 + 2 = 16).

Python Solution

class Solution: def minCost(self, n: int, cuts: List[int]) -> int: cuts.extend([0, n]) cuts.sort() m = len(cuts) f = [[0] * m for _ in range(m)] for l in range(2, m): for i in range(m - l): j = i + l f[i][j] = inf for k in range(i + 1, j): f[i][j] = min(f[i][j], f[i][k] + f[k][j] + cuts[j] - cuts[i]) return f[0][-1]

Complexity

The time complexity is O(m3)O(m^3)O(m3), and the space complexity is O(m2)O(m^2)O(m2). The space complexity is O(m2)O(m^2)O(m2).

Edge Cases and Pitfalls

Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.

Summary

This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.


Ace your next coding interview

We're here to help you ace your next coding interview.

Subscribe
Stealth Interview
© 2026 Stealth Interview®Stealth Interview is a registered trademark. All rights reserved.
Product
  • Blog
  • Pricing
Company
  • Terms of Service
  • Privacy Policy