The Wayback Machine - https://web.archive.org/web/20250524112728/https://www.geeksforgeeks.org/pair-with-given-product-set-1-find-if-any-pair-exists/
Open In App

Check pair with given product

Last Updated : 28 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array arr[] of n distinct integers and a target value, the task is to check whether there is a pair of elements in the array whose product is equal to target.

Examples : 

Input: arr[] = [1, 5, 7, -1, 5], target = 35
Output: true
Explanation: As 5* 7= 35, the answer is true.

Input: arr[] = [-10, 20, 9, -40], target = 30
Output: false
Explanation: No pair exists with product 30

[Naive Approach] By Generating all Possible Pairs - O(n2) time and O(1) space

The very basic approach is to generate all the possible pairs and check if any pair exists whose product is equals to given target value then return true. If no such pair exist then return false.

C++
#include <bits/stdc++.h>
using namespace std;

// Function to check if any pair exists whose product
// equals the target
bool isProduct(vector<int> &arr, long long target) {
    int n = arr.size();
    for (int i = 0; i < n - 1; i++) {
        for (int j = i + 1; j < n; j++) {
            if (1LL * arr[i] * arr[j] == target) {
                return true;
            }
        }
    }
    return false;
}

int main() {
    vector<int> arr = {1, 5, 7, -1, 5};
    long long target = 35;
    cout << isProduct(arr, target) << endl;

    return 0;
}
C
#include <stdio.h>
#include <stdbool.h>

// Function to check if any pair exists whose product
// equals the target
bool isProduct(int arr[], int n, long long target) {
    for (int i = 0; i < n - 1; i++) {
        for (int j = i + 1; j < n; j++) {
            if (1LL * arr[i] * arr[j] == target) {
                return true;
            }
        }
    }
    return false;
}

int main() {
    int arr[] = {1, 5, 7, -1, 5};
    long long target = 35; 
    int n = sizeof(arr) / sizeof(arr[0]);
    printf("%d\n", isProduct(arr, n, target));
    
    return 0;
}
Java
class GfG {

    // Function to check if any pair exists whose product
    // equals the target
    static boolean isProduct(int[] arr, long target) {
        int n = arr.length;
        for (int i = 0; i < n - 1; i++) {
            for (int j = i + 1; j < n; j++) {
                if ((long) arr[i] * arr[j] == target) {
                    return true;
                }
            }
        }
        return false;
    }

    public static void main(String[] args) {
        int[] arr = {1, 5, 7, -1, 5};
        long target = 35; 
        System.out.println(isProduct(arr, target));
    }
}
Python
# Function to check if any pair exists whose product
# equals the target
def is_product(arr, target):
    n = len(arr)
    for i in range(n - 1):
        for j in range(i + 1, n):
            if arr[i] * arr[j] == target:
                return True
    return False

arr = [1, 5, 7, -1, 5]
target = 35
print(is_product(arr, target))
C#
using System;

class GfG {

    // Function to check if any pair exists whose product
    // equals the target
    static bool IsProduct(int[] arr, long target) {
        int n = arr.Length;
        for (int i = 0; i < n - 1; i++) {
            for (int j = i + 1; j < n; j++) {
                if ((long)arr[i] * arr[j] == target) {
                    return true;
                }
            }
        }
        return false;
    }

    static void Main() {
        int[] arr = { 1, 5, 7, -1, 5 };
        long target = 35; 
        Console.WriteLine(IsProduct(arr, target));
    }
}
JavaScript
// Function to check if any pair exists whose product
// equals the target
function isProduct(arr, target) {
    let n = arr.length;
    for (let i = 0; i < n - 1; i++) {
        for (let j = i + 1; j < n; j++) {
            if (arr[i] * arr[j] === target) {
                return true;
            }
        }
    }
    return false;
}

let arr = [1, 5, 7, -1, 5];
let target = 35;
console.log(isProduct(arr, target));

Output
1

Time Complexity: O(n²), for using two nested loops
Auxiliary Space: O(1)

[Better Approach] Using Two Pointer Technique - O(n log(n)) time and O(1) space

We can use the two-pointer technique for this problem as well, but it is applicable only to sorted data. So, first sort the array and keep two pointers one pointer at the beginning (left) and another at the end (right) of the array. Then check the product of the elements at these two pointers:

  • If the product equals the target, we’ve found the pair.
  • If the product is less than the target, move the left pointer to the right to increase the product.
  • If the product is greater than the target, move the right pointer to the left to decrease the product.
C++
#include <bits/stdc++.h>
using namespace std;

// Function to check if any pair exists whose product equals the target.
bool isProduct(vector<int> &arr, long long target) {
  
    // Sort the array
    sort(arr.begin(), arr.end());

    int left = 0, right = arr.size() - 1;

    while (left < right) {
        // Calculate the current product
        long long currProd = 1LL*arr[left]*arr[right];

        // If the product matches the target, return true.
        if (currProd == target) return true;

        // Move the pointers based on comparison with target.
        if (currProd > target) right--;
        else left++;
    }

    return false;
}

int main() {
    vector<int> arr = {1, 5, 7, -1, 5};
    long long target = 35;
    cout << isProduct(arr, target) << endl;

    return 0;
}
C
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>

// Function to compare two integers (used in qsort)
int compare(const void *a, const void *b)
{
    return (*(int *)a - *(int *)b);
}

// Function to check if any pair exists whose product
// equals the target.
bool isProduct(int arr[], int n, long long target)
{
    // Sort the array
    qsort(arr, n, sizeof(int), compare);

    int left = 0, right = n - 1;

    while (left < right)
    {
        // Calculate the current product
        long long currProd = (long long)arr[left] * arr[right];

        // If the product matches the target, return true.
        if (currProd == target)
            return true;

        // Move the pointers based on comparison with target.
        if (currProd > target)
            right--;
        else
            left++;
    }
    return false;
}

int main()
{
    int arr[] = {1, 5, 7, -1, 5};
    long long target = 35;
    int n = sizeof(arr) / sizeof(arr[0]);
    printf("%d\n", isProduct(arr, n, target));
    return 0;
}
Java
import java.util.Arrays;

class GfG {

    // Function to check if any pair exists whose product equals the target.
    static boolean isProduct(int[] arr, long target) {
        // Sort the array
        Arrays.sort(arr);

        int left = 0, right = arr.length - 1;

        while (left < right) {
          
            // Calculate the current product
            long currProd = (long) arr[left] * arr[right];

            // If the product matches the target, return true.
            if (currProd == target) return true;

            // Move the pointers based on comparison with target.
            if (currProd > target) right--;
            else left++;
        }

        return false;
    }

    public static void main(String[] args) {
        int[] arr = {1, 5, 7, -1, 5};
        long target = 35;      
        System.out.println(isProduct(arr, target));
    }
}
Python
# Function to check if any pair exists whose product equals the target.
def isProduct(arr, target):
    # Sort the array
    arr.sort()

    left, right = 0, len(arr) - 1

    while left < right:
      
        # Calculate the current product
        currProd = arr[left] * arr[right]

        # If the product matches the target, return True.
        if currProd == target:
            return True

        # Move the pointers based on comparison with target.
        if currProd > target:
            right -= 1
        else:
            left += 1

    return False

if __name__ == "__main__":
    arr = [1, 5, 7, -1, 5]
    target = 35
    print(isProduct(arr, target))
C#
using System;
using System.Linq;

class GfG {
    // Function to check if any pair exists whose product
    // equals the target.
    static bool isProduct(int[] arr, long target) {
      
        // Sort the array
        Array.Sort(arr);

        int left = 0, right = arr.Length - 1;

        while (left < right) {
            // Calculate the current product
            long currProd = (long) arr[left] * arr[right];

            // If the product matches the target, return true.
            if (currProd == target) return true;

            // Move the pointers based on comparison with target.
            if (currProd > target) right--;
            else left++;
        }

        return false;
    }

    static void Main(string[] args) {
        int[] arr = { 1, 5, 7, -1, 5 };
        long target = 35;   
        Console.WriteLine(isProduct(arr, target));
    }
}
JavaScript
// Function to check if any pair exists whose product
// equals the target.
function isProduct(arr, target) {
    // Sort the array
    arr.sort((a, b) => a - b);

    let left = 0, right = arr.length - 1;

    while (left < right) {
        // Calculate the current product
        let currProd = arr[left] * arr[right];

        // If the product matches the target, return true.
        if (currProd === target) return true;

        // Move the pointers based on comparison with target.
        if (currProd > target) right--;
        else left++;
    }

    return false;
}

let arr = [1, 5, 7, -1, 5];
let target = 35;
console.log(isProduct(arr, target));

Output
1

Time Complexity: O(n log(n)), for sorting the array
Auxiliary Space: O(1)

[Expected Approach] Using HashSet - O(n) time and O(n) space

We can use a hash set for efficiently look up. As we iterate through the array, we check if each number is a factor of the target. If it is then we see if its corresponding factor is already in the set. If so, we return true; otherwise, we add the current number to the set and continue.

C++
#include <iostream>
#include <vector>
#include <unordered_set>

using namespace std;

// Function to check if any pair exists whose product
// equals the target.
bool isProduct(vector<int> &arr, long long target) {
  
    // Use an unordered set to store previously seen numbers.
    unordered_set<int> st;

    for (int num : arr) {
        // If target is 0 and current number is 0, return true.
        if (target == 0 && num == 0) return true;

        // Check if current number can be a factor of the target.
        if (target % num == 0) {
            int secondNum = target / num;
            
            // If the secondNum has been seen before, return true.
            if (st.find(secondNum) != st.end()) {
                return true;
            }
            
            // Mark the current number as seen.
            st.insert(num);
        }
    }
    return false;
}

int main() {
    vector<int> arr = {1, 5, 7, -1, 5};
    long long target = 35;
    cout << isProduct(arr, target) << endl;

    return 0;
}
Java
import java.util.HashSet;

class GfG {

    // Function to check if any pair exists whose product
    // equals the target.
    static boolean isProduct(int[] arr, long target)
    {
        // Use a hash set to store previously seen numbers.
        HashSet<Integer> set = new HashSet<>();

        for (int num : arr) {
            // If target is 0 and current number is 0,
            // return true.
            if (target == 0 && num == 0)
                return true;

            // Check if current number can be a factor of
            // the target.
            if (target % num == 0) {
                int secondNum = (int)(target / num);

                // If the secondNum has been seen before,
                // return true.
                if (set.contains(secondNum))
                    return true;

                // Mark the current number as seen.
                set.add(num);
            }
        }
        return false;
    }

    public static void main(String[] args)
    {
        int[] arr = { 1, 5, 7, -1, 5 };
        long target = 35;
        System.out.println(isProduct(arr, target));
    }
}
Python
# Function to check if any pair exists whose product equals the target.
def isProduct(arr, target):
    # Use a set to store previously seen numbers.
    st = set()

    for num in arr:
        # If target is 0 and current number is 0, return True.
        if target == 0 and num == 0:
            return True

        # Check if current number can be a factor of the target.
        if target % num == 0:
            secondNum = target // num
            
            # If the secondNum has been seen before, return True.
            if secondNum in st:
                return True
            
            # Mark the current number as seen.
            st.add(num)
    
    return False

if __name__ == "__main__":
    arr = [1, 5, 7, -1, 5]
    target = 35
    print(isProduct(arr, target))
C#
using System;
using System.Collections.Generic;

class GfG {
    // Function to check if any pair exists whose product
    // equals the target.
    static bool isProduct(int[] arr, long target)
    {
        // Use a hash set to store previously seen numbers.
        HashSet<int> set = new HashSet<int>();

        foreach(int num in arr)
        {

            // If target is 0 and current number is 0,
            // return true.
            if (target == 0 && num == 0)
                return true;

            // Check if current number can be a factor of
            // the target.
            if (target % num == 0) {
                int secondNum = (int)(target / num);

                // If the secondNum has been seen before,
                // return true.
                if (set.Contains(secondNum))
                    return true;

                // Mark the current number as seen.
                set.Add(num);
            }
        }
        return false;
    }

    static void Main(string[] args)
    {
        int[] arr = { 1, 5, 7, -1, 5 };
        long target = 35;
        Console.WriteLine(isProduct(arr, target));
    }
}
JavaScript
// Function to check if any pair exists whose product equals
// the target.
function isProduct(arr, target)
{
    // Use a set to store previously seen numbers.
    let seen = new Set();

    for (let num of arr) {
        // If target is 0 and current number is 0, return
        // true.
        if (target === 0 && num === 0)
            return true;

        // Check if current number can be a factor of the
        // target.
        if (target % num === 0) {
            let secondNum = target / num;

            // If the secondNum has been seen before, return
            // true.
            if (seen.has(secondNum))
                return true;

            // Mark the current number as seen.
            seen.add(num);
        }
    }
    return false;
}

let arr = [ 1, 5, 7, -1, 5 ];
let target = 35;
console.log(isProduct(arr, target));

Output
1

Time Complexity: O(n), for single iteration
Auxiliary Space: O(n), for storing elements in the hash set


Next Article
Article Tags :
Practice Tags :

Similar Reads