Program to find the product of three elements when all are unique in Python

Sometimes we need to find the product of three numbers, but only when all numbers are unique. If any two numbers are equal, they should not contribute to the final product.

So, if the input is like x = 5, y = 4, z = 2, then the output will be 40, as all three numbers are distinct so their product is 5 * 4 * 2 = 40. However, if x = 5, y = 5, z = 2, the output would be 2 since only z is unique.

Algorithm

To solve this, we will follow these steps −

  • Create a temporary set to track seen numbers
  • Create a remove set to track duplicates
  • For each number in [x,y,z], do
    • If number is already in temp_set, add it to remove set
    • Add number to temp_set
  • Remove all duplicate numbers from temp_set
  • Calculate product of remaining unique numbers
  • Return the product

Example

Let us see the following implementation to get better understanding −

class Solution:
    def solve(self, x, y, z):
        temp_set = set()
        remove = set()
        
        for i in [x, y, z]:
            if i in temp_set:
                remove.add(i)
            temp_set.add(i)
        
        for i in remove:
            temp_set.remove(i)
        
        multiplied = 1
        for i in temp_set:
            multiplied *= i
        
        return multiplied

# Test the solution
ob = Solution()
print(ob.solve(5, 4, 2))
print(ob.solve(5, 5, 2))
print(ob.solve(3, 3, 3))
40
2
1

Alternative Approach Using Counter

We can also use Python's Counter to find unique elements more efficiently −

from collections import Counter

def find_unique_product(x, y, z):
    numbers = [x, y, z]
    count = Counter(numbers)
    
    product = 1
    for num, freq in count.items():
        if freq == 1:  # Only unique numbers
            product *= num
    
    return product

# Test cases
print(find_unique_product(5, 4, 2))
print(find_unique_product(5, 5, 2))
print(find_unique_product(3, 3, 3))
40
2
1

How It Works

The algorithm works by:

  • Step 1: Track all numbers in a set while identifying duplicates
  • Step 2: Remove duplicate numbers from the original set
  • Step 3: Calculate product of remaining unique numbers

For input (5, 4, 2): All numbers are unique, so product = 5 × 4 × 2 = 40

For input (5, 5, 2): Only 2 is unique, so product = 2

For input (3, 3, 3): No unique numbers, so product = 1 (identity element)

Conclusion

This algorithm efficiently finds the product of unique elements by using sets to track duplicates. The Counter approach provides a cleaner alternative for the same logic.

Updated on: 2026-03-25T10:36:56+05:30

668 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements