![]() |
VOOZH | about |
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
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
Final answer : true
true
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
true
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.
true