Search code examples
pythonalgorithmdata-structuresdivide-and-conquer

Finding all pairs that have the product equal to the target number


I know there is an exhaustive solution that iterates through every single number, but how to implement the divide and conquer approach?

With an array of integers without repeated numbers, and a target product integer number, return a set of numbers that include all pairs that have the product equal to the target number.

 def product_pair(num_arr, product):
            """
            :type num_arr: List[int]
            :type product: int
            :rtype: List[int]
            """
        Example 1. Product_pair([3, 5, 9, 10, 23, 53], 20) => []
        Example 2. Product_pair([10, 2, 9, 30, 5, 1], 10) => [10, 2, 5, 1]

Solution

  • Well I'm not so sure about divide and conquer, but this will be rather efficient and quite simple:

    def product_pair(num_arr, product):
        value_set = set(num_arr)
        sol = [n for n in num_arr if product/n in value_set]
        return sol