Product Pair GFG problem

 Product Pair


Given an array, arr[] of distinct elements, and a number x, find if there is a pair in arr[] with a product equal to x. Return true if there exists such pair otherwise false.


Examples:


Input: arr[] = [10, 20, 9, 40], x = 400

Output: true

Explanation: As 10 * 40 = 400, the answer is true.

Input: arr[] = [-10, 20, 9, -40], x = 30

Output: false

Explanation: No pair exists with product 30.

Expected Time Complexity: O(n)

Expected Space Complexity: O(n)



import java.util.*;


class Solution {

    boolean isProduct(int[] arr, long x) {

        Set<Long> seen = new HashSet<>();


        for (int num : arr) {

            long val = (long) num;


            // If x is 0, look for a 0 * anything = 0 (not needed here since values are distinct)

            if (val != 0 && x % val == 0) {

                long pair = x / val;

                if (seen.contains(pair)) {

                    return true;

                }

            }


            // Add the current element to the set

            seen.add(val);

        }


        return false;

    }

}



Comments

Popular posts from this blog

Two Sum II - Input Array Is Sorted

Comparable Vs. Comparator in Java

Increasing Triplet Subsequence