Last Stone Weight Problem Explanation

Given a collection of stones, each having a positive integer weight, perform the following operation: On each turn, select the two heaviest stones and smash them together. Assume the stones have weights 'x' and 'y' where 'x' <= 'y'. The outcomes of smashes are:

  1. If 'x' == 'y', both stones are destroyed.
  2. If 'x' != 'y', the stone with weight 'x' is destroyed, and the stone with weight 'y' is updated to 'y - x'.

Continue this process until at most one stone remains. Return the weight of the last stone, or 0 if no stones are left.

Input:

First line: Integer 'N', the number of stones.
Second line: 'N' space-separated integers representing the weights of the stones.

Output:

Print the weight of the final stone, or 0 if no stones remain.

Example:

Input: 
N = 6
Weights = [2, 7, 4, 1, 8, 1]

Output:
1

Constraints:

  • 1 <= N <= 10^5
  • 1 <= W[i] <= 10^6
  • Time Limit: 1 sec

Note:

Implement the function to solve the problem. No need for explicit printing or input reading as it's handled internally.

AnswerBot
4mo

Implement a function to find the weight of the last stone remaining after smashing the heaviest stones together.

  • Create a max heap to store the weights of stones.

  • Repeatedly pop the two heaviest stones,...read more

Help your peers!
Select
Add answer anonymously...

Top Software Developer Interview Questions Asked at Encore Capital Group

Q. Can you explain a real-time implementation of Object-Oriented Programming and th...read more
Q. Connecting Ropes with Minimum Cost You are given 'N' ropes, each of varying leng...read more
Q. Sum Between Zeroes Problem Statement Given a singly linked list containing a ser...read more
Software Developer Interview Questions
Stay ahead in your career. Get AmbitionBox app
play-icon
play-icon
qr-code
Trusted by over 1.5 Crore job seekers to find their right fit company
80 L+

Reviews

10L+

Interviews

4 Cr+

Salaries

1.5 Cr+

Users

Contribute to help millions

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2025 Info Edge (India) Ltd.

Follow Us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter
Profile Image
Hello, Guest
AmbitionBox Employee Choice Awards 2025
Winners announced!
awards-icon
Contribute to help millions!
Write a review
Write a review
Share interview
Share interview
Contribute salary
Contribute salary
Add office photos
Add office photos
Add office benefits
Add office benefits