Magicsheet logo

Count Square Sum Triples

Easy
100%
Updated 6/1/2025

Asked by 2 Companies

Count Square Sum Triples

What is this problem about?

The "Count Square Sum Triples interview question" is a mathematical enumeration task. You are given an integer nn. You need to find the number of triples (a,b,c)(a, b, c) such that 1a,b,cn1 \leq a, b, c \leq n and a2+b2=c2a^2 + b^2 = c^2. These are also known as Pythagorean triples. Note that (3,4,5)(3, 4, 5) and (4,3,5)(4, 3, 5) are considered two distinct triples.

Why is this asked in interviews?

Companies like Meta and Qualtrics use the "Count Square Sum Triples coding problem" as an introductory technical question. It tests a candidate's ability to implement nested loops efficiently and apply basic mathematical properties (like square roots) to avoid unnecessary computations. It’s a test of "Math interview pattern" and "Enumeration" basics.

Algorithmic pattern used

This problem follows the Nested Loop with Early Exit or Two Sum Square pattern.

  1. Nested Loops: Iterate through all possible values of aa from 1 to nn.
  2. Inner Loop: For each aa, iterate through bb from 1 to nn.
  3. Condition: Calculate a2+b2a^2 + b^2. Let this be SS.
  4. Check Square: Determine if SS is a perfect square (c2c^2) and if its square root cc is less than or equal to nn.
  5. Optimization: Since the equation is symmetric, you can iterate bb from aa to nn and multiply results by 2, or just use the full range for simplicity given the small constraints (n250n \leq 250).

Example explanation

n=5n = 5

  • a=3,b=4a=3, b=4: 32+42=9+16=25=523^2 + 4^2 = 9 + 16 = 25 = 5^2. Since 555 \leq 5, this is a triple.
  • a=4,b=3a=4, b=3: 42+32=25=524^2 + 3^2 = 25 = 5^2. This is another triple. Result: 2. n=10n = 10
  • Triples: (3,4,5), (4,3,5), (6,8,10), (8,6,10). Result: 4.

Common mistakes candidates make

  • Integer Precision: Using sqrt and then squaring back to check for equality without handling potential floating-point precision issues (though not usually an issue for small integers).
  • Over-counting: Including triples where c>nc > n.
  • Redundant Calculation: Recalculating a2a^2 inside the inner loop instead of once in the outer loop.

Interview preparation tip

Always look for the upper bound of your search space. In this problem, because a2+b2=c2a^2 + b^2 = c^2 and cnc \leq n, then aa and bb must also be less than nn. Small mathematical insights can significantly clean up your "Enumeration interview pattern" code.

Similar Questions