Taro Logo

Count Square Sum Triples

#1 Most AskedEasy
0 views
Topics:
Arrays

A square triple (a,b,c) is a triple where a, b, and c are integers and a2 + b2 = c2.

Given an integer n, return the number of square triples such that 1 <= a, b, c <= n.

Example 1:

Input: n = 5
Output: 2
Explanation: The square triples are (3,4,5) and (4,3,5).

Example 2:

Input: n = 10
Output: 4
Explanation: The square triples are (3,4,5), (4,3,5), (6,8,10), and (8,6,10).

Constraints:

  • 1 <= n <= 250

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What is the maximum possible value of $n$ for this problem?
  2. Does the order of $a$ and $b$ matter in the triplet $(a, b, c)$, meaning should $(a, b, c)$ and $(b, a, c)$ be counted as distinct triples?
  3. Are $a$, $b$, and $c$ strictly required to be positive integers, or can they be zero or negative?
  4. Is there a specific time or space complexity constraint I should aim for beyond the optimal solution?
  5. What should be returned if no such triples exist for a given $n$?

Brute Force Solution

Approach

To find all number triplets up to a certain limit where the sum of the squares of the first two numbers equals the square of the third, the brute force approach simply tries every possible combination of three numbers. We examine every single trio within our limit to see if they satisfy the equation.

Here's how the algorithm would work step-by-step:

  1. Choose a number from one up to the given limit to represent the first part of our puzzle.
  2. Choose another number, also within the same limit, to represent the second part.
  3. Choose a third number, still within the limit, to act as the result.
  4. Calculate the square of the first number by multiplying it by itself, and do the exact same thing for the second and third numbers.
  5. Check if the squared value of the first number plus the squared value of the second number equals the squared value of the third number.
  6. If they match, record this combination as a valid answer.
  7. Repeat this entire testing process for every single possible combination of the three numbers until every option has been checked.

Code Implementation

def countTriples(limit: int) -> int:
    # Initialize counter to track valid combinations found
    valid_triples_count = 0

    for first_number in range(1, limit + 1):
        for second_number in range(1, limit + 1):
            for third_number in range(1, limit + 1):
                # Check if current combination satisfies the Pythagorean theorem equation
                if (first_number ** 2) + (second_number ** 2) == (third_number ** 2):
                    valid_triples_count += 1

    # Return total count after evaluating all possible combinations
    return valid_triples_count

Big(O) Analysis

Time Complexity
O(n³) – The brute force approach uses three nested loops, where each loop iterates from 1 up to the input limit n to test every possible combination for the three numbers in the triplet. The first and second loops each run n times to select the first two numbers, while the third loop also runs n times to select the potential result. This drives the cost by exhaustively checking n cubed possible trios of numbers against our Pythagorean condition. Consequently, the total operations approximate n times n times n over a constant factor, which simplifies to the final Big O time complexity of O(n³).
Space Complexity
O(1) – The algorithm only uses a few primitive integer variables to loop through the numbers and track the count of valid triplets. Because no additional data structures, recursion stack frames, or dynamically sized collections are created, the extra memory usage remains constant regardless of the input limit N.

Optimal Solution

Approach

Instead of testing every possible combination of three numbers, the optimal strategy focuses on picking the two smaller numbers and testing if their combined squares can form a valid larger square within the allowed limit. By taking advantage of mathematics and smart boundaries, we avoid doing unnecessary work and quickly find all valid sets.

Here's how the algorithm would work step-by-step:

  1. Choose the first number from the available range of numbers.
  2. Choose a second number from the same range of numbers, keeping in mind it can be the same or different from the first.
  3. Calculate the result of taking the first number times itself and adding it to the second number times itself.
  4. Check if this combined total can be made by multiplying a third whole number by itself, and ensure this third number does not exceed the maximum allowed limit.
  5. If the third number fits within the allowed limit and its square matches the combined total, count it as a valid set.
  6. Repeat this checking process for all possible pairs of the first two numbers.
  7. Add up every successful match found along the way to get the final total count.

Code Implementation

import math


def count_triples(maximum_limit):
    valid_triple_count = 0

    # Iterate through all possible values for the first number in the square sum triple.
    for first_number in range(1, maximum_limit + 1):
        for second_number in range(1, maximum_limit + 1):
            combined_square_sum = (first_number ** 2) + (second_number ** 2)

            # Calculate the integer square root to efficiently check for a valid third number.
            potential_third_number = int(math.isqrt(combined_square_sum))

            # Verify that the squared root matches the sum and stays within the allowed limit.
            if (potential_third_number ** 2 == combined_square_sum) and (potential_third_number <= maximum_limit):
                valid_triple_count += 1

    return valid_triple_count

Big(O) Analysis

Time Complexity
O(n²) – The input size n represents the maximum allowed limit for the numbers in our range. We use two nested loops to iterate through all possible values for the first and second numbers, each running from 1 up to n. For every pair of numbers, we perform a constant time mathematical check to see if their combined squares form a valid third square. This nested combination results in approximately n * n operations, which simplifies to the final Big O time complexity of O(n²).
Space Complexity
O(1) – The algorithm only uses a few primitive integer variables to loop through the first number, the second number, and the potential third number. No additional dynamic data structures, recursive calls, or auxiliary memory allocations scale with the input size N. Therefore, the extra memory remains constant regardless of the value of N, resulting in an optimal auxiliary space complexity.

Edge Cases

Input n is less than 5
How to Handle:
The loops will not find any valid triples where a squared plus b squared equals c squared, correctly returning zero.
Input n is at its maximum constraint limit
How to Handle:
A naive cubic approach would TLE, so we must use an O(n squared) nested loop approach or optimized square root checks to scale efficiently.
Values of a and b are equal
How to Handle:
The algorithm allows a and b to be the same since the problem definition states the tuple elements must only be positive integers less than or equal to n.
No square sum triples exist within the range
How to Handle:
The counter remains at zero and the function successfully returns the initial count without failing.
Large values of n causing integer overflow during squaring
How to Handle:
We should use standard 32-bit or 64-bit integer types which safely accommodate the squared values for the problem constraints.
Floating point precision issues when checking square roots
How to Handle:
Using integer arithmetic like checking if the square root squared equals the original number prevents floating point inaccuracies.
0/5 completed