Bird
Raised Fist0

What is the time complexity of the space-optimized bottom-up DP solution for Last Stone Weight II, where n is the number of stones and sum is the total weight of all stones?

medium🪤 Complexity Trap Q13 of Q15
Dynamic Programming: Knapsack - Last Stone Weight II
What is the time complexity of the space-optimized bottom-up DP solution for Last Stone Weight II, where n is the number of stones and sum is the total weight of all stones?
AO(n + sum)
BO(n^2)
CO(n * sum * log n)
DO(n * sum)
Step-by-Step Solution
  1. Step 1: Identify loops in the code

    Outer loop runs n times (for each stone), inner loop runs up to half the total sum (sum/2).
  2. Step 2: Calculate total operations

    Each iteration updates dp array, so total operations ≈ n * (sum/2) -> O(n * sum).
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    DP complexity depends on n and sum, not n squared or log factors [OK]
Quick Trick: DP loops over stones and sums -> O(n * sum) [OK]
Common Mistakes:
MISTAKES
  • Confusing n with sum leading to O(n^2)
  • Assuming logarithmic factor due to sorting
  • Ignoring that dp array size depends on sum
Trap Explanation:
PITFALL
  • O(n^2) looks plausible if candidate confuses n and sum; sum can be large, so complexity depends on sum.
Interviewer Note:
CONTEXT
  • Checks if candidate understands DP complexity depends on sum dimension, not just input size n.
Master "Last Stone Weight II" in Dynamic Programming: Knapsack

3 interactive learning modes - each teaches the same concept differently

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Dynamic Programming: Knapsack Quizzes