DDSA Solutions

1925. Count Square Sum Triples

Time: O(n²)
Space: O(n)

Problem Overview

Count Square Sum Triples (Unknown) asks you to solve a structured algorithmic task. This is a common Math / enumeration pattern in coding interviews. Brute-force all pairs (a,b); check if a²+b² is a perfect square ≤ n.

A full step-by-step explanation is being added. See the study guide for pattern-based practice.

Approach

Brute-force all pairs (a,b); check if a²+b² is a perfect square ≤ n.

Related patterns: Math, enumeration

1925.cs
C#
// Approach: Brute-force all pairs (a,b); check if a²+b² is a perfect square ≤ n.
// Time: O(n²) Space: O(n)

public class Solution
{
    public int CountTriples(int n)
    {
        int tripleCount = 0;

        // Iterate through all possible values for 'a'
        for (int a = 1; a < n; a++)
        {
            // Iterate through all possible values for 'b'
            for (int b = 1; b < n; b++)
            {
                // Calculate the sum of squares: a^2 + b^2
                int sumOfSquares = a * a + b * b;

                // Calculate the potential value of 'c' using square root
                int c = (int)Math.Sqrt(sumOfSquares);

                // Check if 'c' is within bounds and forms a perfect square
                // (c^2 == sumOfSquares ensures it's a Pythagorean triple)
                if (c <= n && c * c == sumOfSquares)
                    tripleCount++;
            }
        }

        return tripleCount;
    }
}
Was this solution helpful?

Related Problems