Start learning free

LESSON 456 OF 673 · HEAP

Last Stone Weight in Python (Time Complexity: O(n log n)) /homework

Practice O(n log n) Read the full explanation

You get a list stones. Each number is the weight of one stone in a pile.

Each turn, smash the two heaviest stones together. If they weigh the same, both break. If not, the lighter one breaks. The heavier one loses that much weight. For example, stones of 9 and 4 leave one stone of 5.

Repeat until one stone or none is left. Return the weight of that stone, or 0 if none is left.

 

Example 1:

Input: stones = [12, 5, 4, 1]
Output: 2
Explanation: 
Smash 12 and 5. The pile is now [7, 4, 1].
Smash 7 and 4. The pile is now [3, 1].
Smash 3 and 1. Only a stone of 2 is left.

Example 2:

Input: stones = [8, 3, 7, 4]
Output: 0
Explanation: 
Smash 8 and 7. The pile is now [3, 4, 1].
Smash 4 and 3. The pile is now [1, 1].
The two 1s weigh the same, so both break.
Nothing is left.

Example 3:

Input: stones = [6, 6, 6]
Output: 6
Explanation: Two of the 6s smash, and both break.
The third 6 is left.

 

Constraints:

  • 2 to 30,000 stones.
  • Each weight is a whole number from 0 to 100,000,000.
STEP 1 OF 8
    Ctrl + Enter to check

    PYTHON · HEAP

    Last Stone Weight in Python, explained

    Understanding the Problem

    The core challenge of this problem is to repeatedly find and process the two heaviest stones until only one stone remains or all stones are destroyed. This problem is significant in scenarios where we need to repeatedly process the largest elements, such as in certain scheduling or resource allocation problems.

    Potential pitfalls include not efficiently finding the two heaviest stones, which can lead to suboptimal performance.

    Approach

    To solve this problem, we need to efficiently find and process the two heaviest stones. A naive approach would involve sorting the list repeatedly, but this is not optimal. Instead, we can use a max-heap (priority queue) to always access the heaviest stones efficiently.

    Naive Solution

    The naive solution involves sorting the list to find the two heaviest stones, which is inefficient due to the repeated sorting operations.

    Optimized Solution

    Using a max-heap allows us to efficiently find and remove the heaviest stones. In Python, we can use the `heapq` module, which provides a min-heap by default. By storing negative weights, we can simulate a max-heap.

    Algorithm

    1. Convert the list of stone weights into a max-heap by storing negative weights.
    2. While there is more than one stone in the heap:
      1. Extract the two heaviest stones (largest negative values).
      2. If they are not equal, push the difference back into the heap.
    3. If the heap is empty, return 0. Otherwise, return the weight of the remaining stone.

    Code Implementation

    import heapq
    
    def lastStoneWeight(stones):
        # Convert all stone weights to negative to use heapq as a max-heap
        stones = [-stone for stone in stones]
        heapq.heapify(stones)
        
        # Process the stones until one or none is left
        while len(stones) > 1:
            # Extract the two heaviest stones
            first = heapq.heappop(stones)
            second = heapq.heappop(stones)
            
            # If they are not equal, push the difference back into the heap
            if first != second:
                heapq.heappush(stones, first - second)
        
        # If no stones are left, return 0; otherwise, return the weight of the remaining stone
        return -stones[0] if stones else 0
    
    # Example usage
    print(lastStoneWeight([2, 7, 4, 1, 8, 1]))  # Output: 1
    

    Complexity Analysis

    The time complexity of this approach is O(n log n), where n is the number of stones. This is because each insertion and extraction operation on the heap takes O(log n) time, and we perform these operations n-1 times. The space complexity is O(n) due to the storage of the heap.

    Edge Cases

    Potential edge cases include:

    • All stones having the same weight.
    • Only one stone in the input list.
    • No stones in the input list.

    These cases are handled by the algorithm as it processes the heap until one or no stones are left.

    Testing

    To test the solution comprehensively, consider the following test cases:

    • Simple cases with a few stones.
    • Cases with all stones having the same weight.
    • Cases with only one stone.
    • Cases with no stones.

    Using a testing framework like `unittest` in Python can help automate and validate these test cases.

    Thinking and Problem-Solving Tips

    When approaching such problems, consider the following tips:

    • Break down the problem into smaller, manageable parts.
    • Think about data structures that can optimize the operations you need to perform.
    • Practice similar problems to improve your problem-solving skills.

    Conclusion

    Understanding and solving the "Last Stone Weight" problem helps improve your skills in using heaps and priority queues. It also highlights the importance of choosing the right data structures for efficient problem-solving.

    Keep practicing and exploring further to enhance your algorithmic thinking and coding skills.

    Additional Resources

    Keep going with Python650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free