Among 20 spheres, one sphere's weight is larger than the other 19 spheres. How will you find that sphere without seeing it? Explain the logic and code.

AnswerBot
2y

Finding the heavier sphere among 20 spheres without seeing it.

  • Divide the spheres into groups of 3, weigh any two groups against each other.

  • If both groups weigh the same, the heavier sphere is in the t...read more

Rocky Saini
2y

public class FindHeavierSphere {

public static void main(String[] args) {

int[] spheres = new int[20];

// Assign weights to the spheres, where one sphere has a higher weight

int heavierSphere = findHeavierSphere(spheres);

System.out.println("The heavier sphere is: " + heavierSphere);

}

public static int findHeavierSphere(int[] spheres) {

// Divide the spheres into groups A, B, and C

int[] groupA = new int[6];

int[] groupB = new int[6];

int[] groupC = new int[2];

// Weigh group A against group B

int weightComparison = weighGroups(groupA, groupB);

if (weightComparison == 0) {

// The heavier sphere is in group C

return weighIndividuals(groupC[0], groupC[1]);

} else if (weightComparison > 0) {

// The heavier sphere is in group A

return weighIndividuals(groupA[0], groupA[1]);

} else {

// The heavier sphere is in group B

return weighIndividuals(groupB[0], groupB[1]);

}

}

public static int weighGroups(int[] groupA, int[] groupB) {

int totalWeightA = calculateTotalWeight(groupA);

int totalWeightB = calculateTotalWeight(groupB);

return Integer.compare(totalWeightA, totalWeightB);

}

public static int weighIndividuals(int sphere1, int sphere2) {

return Integer.compare(sphere1, sphere2);

}

public static int calculateTotalWeight(int[] group) {

int totalWeight = 0;

for (int weight : group) {

totalWeight += weight;

}

return totalWeight;

}

}

Help your peers!
Select
Add answer anonymously...
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