Program to check if the given list has Pythagorean Triplets or not in Python

A Pythagorean triplet is a set of three numbers a, b, and c such that a² + b² = c². Given a list of numbers, we need to check whether there exist three numbers that form a Pythagorean triplet.

So, if the input is like [10, 2, 8, 5, 6], then the output will be True, as 8² + 6² = 64 + 36 = 100 = 10².

Algorithm

To solve this problem efficiently, we will follow these steps ?

  • Create a list of squares of all numbers in descending order
  • For each square (potential c²), use two pointers to find if there exist two other squares that sum to it
  • Use left and right pointers to check if any two squares add up to the current base square
  • If found, return True; otherwise, continue searching

Example

Let us see the implementation to get better understanding ?

class Solution:
    def solve(self, nums):
        # Create list of squares in descending order
        tmp = sorted([n*n for n in nums], reverse=True)
        
        for i, n in enumerate(tmp):
            base = n  # This will be c²
            left = i + 1
            right = len(tmp) - 1
            
            # Use two pointers to find a² + b² = c²
            while left < right:
                sum_of_squares = tmp[left] + tmp[right]
                
                if sum_of_squares == base:
                    return True
                elif sum_of_squares > base:
                    left += 1
                else:
                    right -= 1
        
        return False

# Test the solution
ob = Solution()
result = ob.solve([10, 2, 8, 5, 6])
print(f"Input: [10, 2, 8, 5, 6]")
print(f"Output: {result}")

# Let's verify: 6² + 8² = 36 + 64 = 100 = 10²
print(f"Verification: 6² + 8² = {6**2} + {8**2} = {6**2 + 8**2} = 10² = {10**2}")
Input: [10, 2, 8, 5, 6]
Output: True
Verification: 6² + 8² = 36 + 64 = 100 = 10² = 100

How It Works

The algorithm works by:

  • Sorting squares: We sort squares in descending order so the largest square (potential c²) comes first
  • Two-pointer technique: For each potential c², we use two pointers to find if there exist a² and b² such that a² + b² = c²
  • Efficient search: The two-pointer approach reduces time complexity compared to checking all combinations

Alternative Approach

Here's a simpler approach using a set for faster lookup ?

def has_pythagorean_triplet(nums):
    # Create a set of squares for O(1) lookup
    squares = set(n*n for n in nums)
    
    # Check all pairs to see if their sum exists in the set
    nums_sorted = sorted(nums)
    n = len(nums_sorted)
    
    for i in range(n):
        for j in range(i + 1, n):
            a, b = nums_sorted[i], nums_sorted[j]
            c_squared = a*a + b*b
            
            if c_squared in squares:
                return True
    
    return False

# Test the function
numbers = [10, 2, 8, 5, 6]
result = has_pythagorean_triplet(numbers)
print(f"Input: {numbers}")
print(f"Has Pythagorean triplet: {result}")
Input: [10, 2, 8, 5, 6]
Has Pythagorean triplet: True

Conclusion

Both approaches efficiently check for Pythagorean triplets. The first method uses two pointers with sorted squares, while the second uses a set for faster lookup. Choose based on your preference for readability versus optimization.

Updated on: 2026-03-25T11:04:26+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements