Logo
    Logo

    ©️ 2020-2026, Akhil Abraham.

    LinkedInGitHubMediumX
    Akhil Abraham
    Akhil Abraham
    /Posts
    Posts
    /LeetCode
    LeetCode
    /
    LeetCode
    /1046 - Last Stone Weight
    1046 - Last Stone Weight
    1046 - Last Stone Weight
    1046 - Last Stone Weight

    1046 - Last Stone Weight

    Difficulty
    Easy
    Language
    Python
    URL
    https://leetcode.com/problems/last-stone-weight/

    Solution 1 - Brute Force

    Iterate through every pair of numbers using two nested loops. For each pair, check if they sum to the target. Return the indices when a match is found.

    TimeComplexity:O(n2)TimeComplexity: O(n^2)TimeComplexity:O(n2)
    SpaceComplexity:O(1)SpaceComplexity: O(1)SpaceComplexity:O(1)

    Solution 2 - Brute Force using enumerate()

    Same brute force logic, but uses Python's enumerate() for cleaner index tracking instead of range(len(...)).

    TimeComplexity:O(n2)TimeComplexity: O(n^2)TimeComplexity:O(n2)
    SpaceComplexity:O(1)SpaceComplexity: O(1)SpaceComplexity:O(1)

    Solution 1 - Sorting Approach

    Repeatedly sort the array in descending order, take the two heaviest stones, smash them, and insert the result back if non-zero. Continue until one or zero stones remain.

    TimeComplexity:O(n2log⁡n)TimeComplexity: O(n^2 \log n)TimeComplexity:O(n2logn)
    SpaceComplexity:O(1)SpaceComplexity: O(1)SpaceComplexity:O(1)

    Solution 2 - Max Heap (Optimal)

    Use a max heap (simulated with negative values in Python's heapq min-heap) to efficiently retrieve the two heaviest stones each round. Push the difference back if non-zero. Continue until one or zero stones remain.

    TimeComplexity:O(nlog⁡n)TimeComplexity: O(n \log n)TimeComplexity:O(nlogn)
    SpaceComplexity:O(n)SpaceComplexity: O(n)SpaceComplexity:O(n)
    """ 0001.1 - Solution 1 - Brute Force Approach """
    
    #####################################################################################
    # Imports
    #####################################################################################
    from typing import List
    
    #####################################################################################
    # Classes
    #####################################################################################
    class Solution:
        """Solution Class"""
    
        def twoSum(self, nums: List[int], target: int) -> List[int]:
            """Two Sum Function"""
            for i in range(len(nums)):
                for j in range(i + 1, len(nums)):
                    if nums[i] + nums[j] == target:
                        return [i, j]
    
    
    #####################################################################################
    # Functions
    #####################################################################################
    def testcase():
        """Test Function"""
        print(Solution().twoSum([3, 3], 6))
        print(Solution().twoSum([3, 2, 4], 6))
        print(Solution().twoSum([2, 7, 11, 15], 9))
    
    
    #####################################################################################
    # Main
    #####################################################################################
    if __name__ == "__main__":
        testcase()
    
    """ 0001.1 - Solution 1 - Using Enumerate """
    
    #####################################################################################
    # Imports
    #####################################################################################
    from typing import List
    
    #####################################################################################
    # Classes
    #####################################################################################
    class Solution:
        """Solution Class"""
    
        def twoSum(self, nums: List[int], target: int) -> List[int]:
            """Two Sum Function"""
            for key1, num1 in enumerate(nums):
                for key2, num2 in enumerate(nums[key1 + 1 :], key1 + 1):
    	              # enumerate(iterable, start=1) -> start value determines starting index
                    # Printing value and key will output 1 i , 2 j, 3 k, 4 l 
                    if num1 + num2 == target:
                        return [key1, key2]
    
    
    #####################################################################################
    # Functions
    #####################################################################################
    def testcase():
        """Test Function"""
        print(Solution().twoSum([3, 3], 6))
        print(Solution().twoSum([3, 2, 4], 6))
        print(Solution().twoSum([2, 7, 11, 15], 9))
    
    
    #####################################################################################
    # Main
    #####################################################################################
    if __name__ == "__main__":
        testcase()
    
    """ 1046.1 - Last Stone Weight - Solution 1 - Sorting Approach """
    
    #####################################################################################
    # Imports
    #####################################################################################
    from typing import List
    
    #####################################################################################
    # Classes
    #####################################################################################
    class Solution:
        """Solution Class"""
    
        def lastStoneWeight(self, stones: List[int]) -> int:
            """Last Stone Weight Function"""
            while len(stones) > 1:
                stones.sort(reverse=True)
                y = stones.pop(0)
                x = stones.pop(0)
                if y != x:
                    stones.append(y - x)
            return stones[0] if stones else 0
    
    
    #####################################################################################
    # Functions
    #####################################################################################
    def testcase():
        """Test Function"""
        print(Solution().lastStoneWeight([2, 7, 4, 1, 8, 1]))  # Expected: 1
        print(Solution().lastStoneWeight([1]))                   # Expected: 1
        print(Solution().lastStoneWeight([2, 2]))                # Expected: 0
    
    
    #####################################################################################
    # Main
    #####################################################################################
    if __name__ == "__main__":
        testcase()
    
    """ 1046.2 - Last Stone Weight - Solution 2 - Max Heap """
    
    #####################################################################################
    # Imports
    #####################################################################################
    import heapq
    from typing import List
    
    #####################################################################################
    # Classes
    #####################################################################################
    class Solution:
        """Solution Class"""
    
        def lastStoneWeight(self, stones: List[int]) -> int:
            """Last Stone Weight Function"""
            # Python only has a min-heap, so negate values to simulate a max-heap
            heap = [-s for s in stones]
            heapq.heapify(heap)
    
            while len(heap) > 1:
                y = -heapq.heappop(heap)  # heaviest
                x = -heapq.heappop(heap)  # second heaviest
                if y != x:
                    heapq.heappush(heap, -(y - x))
    
            return -heap[0] if heap else 0
    
    
    #####################################################################################
    # Functions
    #####################################################################################
    def testcase():
        """Test Function"""
        print(Solution().lastStoneWeight([2, 7, 4, 1, 8, 1]))  # Expected: 1
        print(Solution().lastStoneWeight([1]))                   # Expected: 1
        print(Solution().lastStoneWeight([2, 2]))                # Expected: 0
    
    
    #####################################################################################
    # Main
    #####################################################################################
    if __name__ == "__main__":
        testcase()