Product Pair (original) (raw)
Given an integer array **arr[] and an integer **target, determine whether there exists a pair of elements in the array whose product is equal to target.
Return **true if such a pair exists; otherwise, return **false.
**Examples :
**Input: arr[] = [10, 20, 9, 40], target = 400
**Output: true
**Explanation: As 10 * 40 = 400, the answer is true.**Input: arr[] = [-10, 20, 9, -40], target = 30
**Output: false
**Explanation: No pair exists with product 30.
Table of Content
- [Naive Approach] By Generating all Possible Pairs - O(n^2) Time and O(1) Space
- [Better Approach] Using Sorting and Two Pointer Technique - O(n log n) Time and O(1) Space
- [Expected Approach] Using Hashing - O(n) Time and O(n) Space
[Naive Approach] By Generating all Possible Pairs - O(n^2) Time and O(1) Space
The very basic approach is to use two nested loops 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 exists then return false.
Consider the following dry run for better understanding: arr = {10, 20, 9, 40}, target = 400
- For i = 0, j = 1 --> Pair = (10, 20) --> Product = 10 × 20 = 200 --> 200 != 400 --> continue
- For i = 0, j = 2 --> Pair = (10, 9) --> Product = 10 × 9 = 90 --> 90 != 400 --> continue
- For i = 0, j = 3 --> Pair = (10, 40) --> Product = 10 × 40 = 400 --> 400 == 400 --> Pair found --> return true
Final answer : true
C++ `
#include #include using namespace std;
// Function to check if any pair has product equal to target bool isProduct(vector &arr, long long target) { int n = arr.size();
// Traverse all possible pairs
for (int i = 0; i < n - 1; i++)
{
for (int j = i + 1; j < n; j++)
{
// Check if product of current pair equals target
if (1LL * arr[i] * arr[j] == target)
{
return true;
}
}
}
return false;}
int main() { vector arr = {10, 20, 9, 40}; long long target = 400;
if (isProduct(arr, target))
cout << "true" << endl;
else
cout << "false" << endl;
return 0;}
C
#include <stdbool.h> #include <stdio.h>
// Function to check if any pair has product equal to target bool isProduct(int arr[], int n, long long target) { // Traverse all possible pairs for (int i = 0; i < n - 1; i++) { for (int j = i + 1; j < n; j++) { // Check if product of current pair equals target if ((long long)arr[i] * arr[j] == target) { return true; } } }
return false;}
int main() { int arr[] = {10, 20, 9, 40}; int n = sizeof(arr) / sizeof(arr[0]); long long target = 400;
if (isProduct(arr, n, target))
printf("true\n");
else
printf("false\n");
return 0;}
Java
public class GfG { // Function to check if any pair has product equal to // target public static boolean isProduct(int[] arr, long target) { int n = arr.length;
// Traverse all possible pairs
for (int i = 0; i < n - 1; i++) {
for (int j = i + 1; j < n; j++) {
// Check if product of current pair equals
// target
if ((long)arr[i] * arr[j] == target) {
return true;
}
}
}
return false;
}
public static void main(String[] args)
{
int[] arr = {10, 20, 9, 40};
long target = 400;
if (isProduct(arr, target))
System.out.println("true");
else
System.out.println("false");
}}
Python
Function to check if any pair has product equal to target
def isProduct(arr, target): n = len(arr)
# Traverse all possible pairs
for i in range(n - 1):
for j in range(i + 1, n):
# Check if product of current pair equals target
if arr[i] * arr[j] == target:
return True # Pair found
return FalseDriver Code
if name == "main": arr = [10, 20, 9, 40] target = 400
if isProduct(arr, target):
print("true")
else:
print("false")C#
using System;
class GfG { // Function to check if any pair has product equal to // target static bool isProduct(int[] arr, long target) { int n = arr.Length;
// Traverse all possible pairs
for (int i = 0; i < n - 1; i++) {
for (int j = i + 1; j < n; j++) {
// Check if product of current pair equals
// target
if ((long)arr[i] * arr[j] == target) {
return true; // Pair found
}
}
}
return false;
}
static void Main()
{
int[] arr = {10, 20, 9, 40};
long target = 400;
if (isProduct(arr, target))
Console.WriteLine("true");
else
Console.WriteLine("false");
}}
JavaScript
// Function to check if any pair has product equal to target function isProduct(arr, target) { let n = arr.length;
// Traverse all possible pairs
for (let i = 0; i < n - 1; i++) {
for (let j = i + 1; j < n; j++) {
// Check if product of current pair equals
// target
if (arr[i] * arr[j] === target) {
return true;
}
}
}
return false;}
// Driver Code let arr = [10, 20, 9, 40]; let target = 400;
if (isProduct(arr, target)) console.log("true"); else console.log("false");
`
[Better Approach] Using Sorting and Two Pointer Technique - O(n log n) Time and O(1) Space
The idea is to Sort the array and use two pointers: one at the beginning (left) and one at the end (right). Compute the product of elements at both pointers. If it equals the target, return true. If the product is smaller, move left forward; if larger, move right backward. Sorting helps in adjusting the product efficiently using pointer movement.
Consider the following dry run : arr = {10, 20, 9, 40}, target = 400
Sort the array: arr = {9, 10, 20, 40}
For i = 0, j = 3 --> arr[i] = 9 and arr[j] = 40 --> 9 * 40 = 360 < target --> i++
For i = 1, j = 3 --> arr[i] = 10 and arr[j] = 40 --> 10 * 40 = 400 == target ---> return true
Final answer : true
C++ `
#include #include #include using namespace std;
// Function to check if any pair has product equal to target bool isProduct(vector &arr, long long target) { // Sort the array sort(arr.begin(), arr.end());
// Initialize two pointers
int left = 0, right = arr.size() - 1;
// Traverse using two pointers
while (left < right)
{
// Calculate current product safely using long long
long long currProd = 1LL * arr[left] * arr[right];
// If product matches target → pair found
if (currProd == target)
return true;
// If product is greater → decrease it
if (currProd > target)
right--;
// If product is smaller → increase it
else
left++;
}
// No pair found
return false;}
int main() { vector arr = {10, 20, 9, 40}; long long target = 400;
if (isProduct(arr, target))
cout << "true" << endl;
else
cout << "false" << endl;
return 0;}
C
#include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h>
// Comparator function for qsort (ascending order) int cmp(const void *a, const void b) { return ((int *)a - *(int *)b); }
// Function to check if any pair has product equal to target bool isProduct(int *arr, int arrSize, long long target) { // Sort the array qsort(arr, arrSize, sizeof(int), cmp);
// Initialize two pointers
int left = 0, right = arrSize - 1;
// Traverse using two pointers
while (left < right)
{
// Calculate current product using long long to avoid overflow
long long currProd = 1LL * arr[left] * arr[right];
// If product matches target → pair found
if (currProd == target)
return true;
// If product is greater → move right pointer left
if (currProd > target)
right--;
// If product is smaller → move left pointer right
else
left++;
}
return false;}
int main() { int arr[] = {10, 20, 9, 40}; long long target = 400;
if (isProduct(arr, sizeof(arr) / sizeof(arr[0]), target))
printf("true\n");
else
printf("false\n");
return 0;}
Java
import java.util.*;
public class GfG { // Function to check if any pair has product equal to // target public static boolean isProduct(int[] arr, long target) { // Sort the array Arrays.sort(arr);
// Initialize two pointers
int left = 0, right = arr.length - 1;
// Traverse using two pointers
while (left < right) {
// Calculate current product safely using long
long currProd = (long)arr[left] * arr[right];
// If product matches target → pair found
if (currProd == target)
return true;
// If product is greater → decrease it
if (currProd > target)
right--;
// If product is smaller → increase it
else
left++;
}
// No pair found
return false;
}
public static void main(String[] args)
{
int[] arr = { 10, 20, 9, 40 };
long target = 400;
if (isProduct(arr, target))
System.out.println("true");
else
System.out.println("false");
}}
Python
def isProduct(arr, target): # Sort the array arr.sort()
# Initialize two pointers
left = 0
right = len(arr) - 1
# Traverse using two pointers
while left < right:
# Calculate current product safely using long long
currProd = arr[left] * arr[right]
# If product matches target → pair found
if currProd == target:
return True
# If product is greater → decrease it
if currProd > target:
right -= 1
# If product is smaller → increase it
else:
left += 1
# No pair found
return FalseDriver Code
if name == "main": arr = [10, 20, 9, 40] target = 400
if isProduct(arr, target):
print("true")
else:
print("false")C#
using System; using System.Linq;
public class GfG { // Function to check if any pair has product equal to // target static bool isProduct(int[] arr, long target) { // Sort the array Array.Sort(arr);
// Initialize two pointers
int left = 0, right = arr.Length - 1;
// Traverse using two pointers
while (left < right) {
// Calculate current product safely using long
long currProd = (long)arr[left] * arr[right];
// If product matches target → pair found
if (currProd == target)
return true;
// If product is greater → decrease it
if (currProd > target)
right--;
// If product is smaller → increase it
else
left++;
}
// No pair found
return false;
}
public static void Main()
{
int[] arr = { 10, 20, 9, 40 };
long target = 400;
if (isProduct(arr, target))
Console.WriteLine("true");
else
Console.WriteLine("false");
}}
JavaScript
function isProduct(arr, target) { // Sort the array arr.sort((a, b) => a - b);
// Initialize two pointers
let left = 0, right = arr.length - 1;
// Traverse using two pointers
while (left < right) {
// Calculate current product safely using BigInt
let currProd
= BigInt(arr[left]) * BigInt(arr[right]);
// If product matches target → pair found
if (currProd == target)
return true;
// If product is greater → decrease it
if (currProd > target)
right--;
// If product is smaller → increase it
else
left++;
}
// No pair found
return false;}
// Driver Code let arr = [ 10, 20, 9, 40 ]; let target = BigInt(400);
if (isProduct(arr, target)) console.log("true"); else console.log("false");
`
[Expected Approach] Using Hashing - O(n) Time and O(n) Space
The idea is to check if there exists a pair whose product equals the target. For each element num, we look for target / num in a hash set of previously seen elements, allowing constant-time lookup and an efficient solution.
C++ `
#include #include #include
using namespace std;
bool isProduct(vector &arr, long long target) { // Use an unordered set to store previously seen numbers. unordered_set 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;}
// Main function int main() { vector arr = {10, 20, 9, 40}; long long target = 400;
if (isProduct(arr, target))
cout << "true";
else
cout << "false";
return 0;}
Java
import java.util.HashSet; import java.util.Set;
public class GfG { public static boolean isProduct(int[] arr, long target) { // Use a set to store previously seen numbers. Set st = 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 (st.contains(secondNum)) {
return true;
}
// Mark the current number as seen.
st.add(num);
}
}
return false;
}
public static void main(String[] args)
{
int[] arr = { 10, 20, 9, 40 };
long target = 400;
if (isProduct(arr, target))
System.out.println("true");
else
System.out.println("false");
}}
Python
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 FalseDriver Code
if name == "main": arr = [10, 20, 9, 40] target = 400
if isProduct(arr, target):
print('true')
else:
print('false')C#
using System; using System.Collections.Generic;
public class GfG { static bool isProduct(int[] arr, long target) { // Use a HashSet to store previously seen numbers. HashSet st = new HashSet();
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 (st.Contains(secondNum)) {
return true;
}
// Mark the current number as seen.
st.Add(num);
}
}
return false;
}
public static void Main()
{
int[] arr = { 10, 20, 9, 40 };
long target = 400;
if (isProduct(arr, target))
Console.WriteLine("true");
else
Console.WriteLine("false");
}}
JavaScript
function isProduct(arr, target) { // Use a set to store previously seen numbers. let st = 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 = Math.floor(target / num);
// If the secondNum has been seen before, return
// true.
if (st.has(secondNum)) {
return true;
}
// Mark the current number as seen.
st.add(num);
}
}
return false;}
// Driver Code let arr = [ 10, 20, 9, 40 ]; let target = 400;
if (isProduct(arr, target)) { console.log("true"); } else { console.log("false"); }
`