Count all possible pairs in given Array with product K
Last Updated :
23 Jul, 2025
Given an integer array arr[] of size N and a positive integer K, the task is to count all the pairs in the array with a product equal to K.
Examples:
Input: arr[] = {1, 2, 16, 4, 4, 4, 8 }, K=16
Output: 5
Explanation: Possible pairs are (1, 16), (2, 8), (4, 4), (4, 4), (4, 4)
Input: arr[] = {1, 10, 20, 10, 4, 5, 5, 2 }, K=20
Output: 5
Explanation: Possible pairs are (1, 20), (2, 10), (2, 10), (4, 5), (4, 5)
Naive Approach:
The naive approach for the problem is to run two nested loops to generate each possible pair and then for each pair generated check their product value. If their product comes out to be same as K then increment the count.
Algorithm:
- Initialize a variable count as 0.
- Traverse the array from index i=0 to i=N-1.
- For each i, traverse the array from index j=i+1 to j=N-1.
- For each pair (i,j), check if their product is equal to K.
- If their product is equal to K, increment the count.
- After completing the loops, return the count.
Below is the implementation of the approach:
C++
// C++ code for the approach
#include <bits/stdc++.h>
using namespace std;
// Function to count pairs with product equal to K
int countPairsWithProductK(int arr[], int n, int k) {
int count = 0;
// Traverse through all possible pairs of the array
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
// Check if the product of the current pair is equal to K
if (arr[i] * arr[j] == k) {
count++;
}
}
}
// Return the count of pairs with product equal to K
return count;
}
// Driver's code
int main() {
int arr[] = { 1, 2, 16, 4, 4, 4, 8 };
int n = sizeof(arr) / sizeof(arr[0]);
int k = 16;
// Function Call
int result = countPairsWithProductK(arr, n, k);
// Print the result
cout << result << endl;
return 0;
}
Java
import java.util.*;
public class Main {
// Function to count pairs with product equal to K
static int countPairsWithProductK(int[] arr, int k) {
int count = 0;
int n = arr.length;
// Traverse through all possible pairs of the array
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
// Check if the product of the current pair is equal to K
if (arr[i] * arr[j] == k) {
count++;
}
}
}
// Return the count of pairs with product equal to K
return count;
}
// Driver's code
public static void main(String[] args) {
int[] arr = { 1, 2, 16, 4, 4, 4, 8 };
int k = 16;
// Function Call
int result = countPairsWithProductK(arr, k);
// Print the result
System.out.println(result);
}
}
Python3
# Function to count pairs with product equal to K
def countPairsWithProductK(arr, k):
count = 0
n = len(arr)
# Traverse through all possible pairs of the array
for i in range(n):
for j in range(i + 1, n):
# Check if the product of the current pair is equal to K
if arr[i] * arr[j] == k:
count += 1
# Return the count of pairs with product equal to K
return count
# Driver's code
arr = [1, 2, 16, 4, 4, 4, 8]
k = 16
# Function Call
result = countPairsWithProductK(arr, k)
# Print the result
print(result)
C#
using System;
class CountPairsWithProductK {
// Function to count pairs with product equal to K
static int CountPairs(int[] arr, int n, int k)
{
int count = 0;
// Traverse through all possible pairs of the array
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
// Check if the product of the current pair
// is equal to K
if (arr[i] * arr[j] == k) {
count++;
}
}
}
// Return the count of pairs with product equal to K
return count;
}
// Driver program to test CountPairs
static void Main()
{
int[] arr = { 1, 2, 16, 4, 4, 4, 8 };
int n = arr.Length;
int k = 16;
// Function Call
int result = CountPairs(arr, n, k);
// Print the result
Console.WriteLine(result);
}
}
JavaScript
// Function to count pairs with product equal to K
function countPairsWithProductK(arr, k) {
let count = 0;
const n = arr.length;
// Traverse through all possible pairs of the array
for (let i = 0; i < n; i++) {
for (let j = i + 1; j < n; j++) {
// Check if the product of the current pair is equal to K
if (arr[i] * arr[j] === k) {
count++;
}
}
}
// Return the count of pairs with product equal to K
return count;
}
// Driver's code
const arr = [1, 2, 16, 4, 4, 4, 8];
const k = 16;
// Function Call
const result = countPairsWithProductK(arr, k);
// Print the result
console.log(result);
Time Complexity: O(N*N) because two nested loops are executing. Here, N is size of input array.
Space Complexity: O(1) as no extra space has been used.
Approach: The idea is to use hashing to store the elements and check if K/arr[i] exists in the array or not using the map and increase the count accordingly.
Follow the steps below to solve the problem:
- Initialize the variable count as 0 to store the answer.
- Initialize the unordered_map<int, int> mp[].
- Iterate over the range [0, N) using the variable i and store the frequencies of all elements of the array arr[] in the map mp[].
- Iterate over the range [0, N) using the variable i and perform the following tasks:
- Initialize the variable index as K/arr[i].
- If K is not a power of 2 and index is present in map mp[] then increase the value of count by mp[arr[i]]*mp[index] and erase both of them from the map mp[].
- If K is a power of 2 and index is present in map mp[] then increase the value of count by mp[index]*(mp[index]-1)/2 and erase it from the map mp[].
- After performing the above steps, print the value of count as the answer.
Below is the implementation of the above approach.
C++14
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to count
// the total number of pairs
int countPairsWithProductK(
int arr[], int n, int k)
{
int count = 0;
// Initialize hashmap.
unordered_map<int, int> mp;
// Insert array elements to hashmap
for (int i = 0; i < n; i++) {
mp[arr[i]]++;
}
for (int i = 0; i < n; i++) {
double index = 1.0 * k / arr[i];
// If k is not power of two
if (index >= 0
&& ((index - (int)(index)) == 0)
&& mp.find(k / arr[i]) != mp.end()
&& (index != arr[i])) {
count += mp[arr[i]] * mp[index];
// After counting erase the element
mp.erase(arr[i]);
mp.erase(index);
}
// If k is power of 2
if (index >= 0
&& ((index - (int)(index)) == 0)
&& mp.find(k / arr[i]) != mp.end()
&& (index == arr[i])) {
// Pair count
count += (mp[arr[i]]
* (mp[arr[i]] - 1))
/ 2;
// After counting erase the element;
mp.erase(arr[i]);
}
}
return count;
}
// Driver Code
int main()
{
int arr[] = { 1, 2, 16, 4, 4, 4, 8 };
int N = sizeof(arr) / sizeof(arr[0]);
int K = 16;
cout << countPairsWithProductK(arr, N, K);
return 0;
}
Java
// Java program for the above approach
import java.util.*;
class GFG{
// Function to count
// the total number of pairs
static int countPairsWithProductK(
int arr[], int n, int k)
{
int count = 0;
// Initialize hashmap.
HashMap<Integer,Integer> mp = new HashMap<Integer,Integer>();
// Insert array elements to hashmap
for (int i = 0; i < n; i++) {
if(mp.containsKey(arr[i])){
mp.put(arr[i], mp.get(arr[i])+1);
}else{
mp.put(arr[i], 1);
}
}
for (int i = 0; i < n; i++) {
int index = (int) (1.0 * k / arr[i]);
// If k is not power of two
if (index >= 0
&& ((index - (int)(index)) == 0)
&& mp.containsKey(k / arr[i])
&& (index != arr[i])) {
count += mp.get(arr[i]) * mp.get(index);
// After counting erase the element
mp.remove(arr[i]);
mp.remove(index);
}
// If k is power of 2
if (index >= 0
&& ((index - (int)(index)) == 0)
&& mp.containsKey(k / arr[i])
&& (index == arr[i])) {
// Pair count
count += (mp.get(arr[i])
* (mp.get(arr[i]) - 1))
/ 2;
// After counting erase the element;
mp.remove(arr[i]);
}
}
return count;
}
// Driver Code
public static void main(String[] args)
{
int arr[] = { 1, 2, 16, 4, 4, 4, 8 };
int N = arr.length;
int K = 16;
System.out.print(countPairsWithProductK(arr, N, K));
}
}
// This code is contributed by 29AjayKumar
Python3
# Python 3 program for the above approach
from collections import defaultdict
# Function to count
# the total number of pairs
def countPairsWithProductK(arr, n, k):
count = 0
# Initialize hashmap.
mp = defaultdict(int)
# Insert array elements to hashmap
for i in range(n):
mp[arr[i]] += 1
for i in range(n):
index = 1.0 * k / arr[i]
# If k is not power of two
if (index >= 0
and ((index - (int)(index)) == 0)
and (k / arr[i]) in mp
and (index != arr[i])):
count += mp[arr[i]] * mp[index]
# After counting erase the element
del mp[arr[i]]
del mp[index]
# If k is power of 2
if (index >= 0
and ((index - (int)(index)) == 0)
and (k / arr[i]) in mp
and (index == arr[i])):
# Pair count
count += ((mp[arr[i]]
* (mp[arr[i]] - 1)) / 2)
# After counting erase the element;
del mp[arr[i]]
return count
# Driver Code
if __name__ == "__main__":
arr = [1, 2, 16, 4, 4, 4, 8]
N = len(arr)
K = 16
print(int(countPairsWithProductK(arr, N, K)))
# This code is contributed by ukasp.
C#
// C# program for the above approach
using System;
using System.Collections.Generic;
public class GFG{
// Function to count
// the total number of pairs
static int countPairsWithProductK(
int []arr, int n, int k)
{
int count = 0;
// Initialize hashmap.
Dictionary<int,int> mp = new Dictionary<int,int>();
// Insert array elements to hashmap
for (int i = 0; i < n; i++) {
if(mp.ContainsKey(arr[i])){
mp[arr[i]] = mp[arr[i]]+1;
}else{
mp.Add(arr[i], 1);
}
}
for (int i = 0; i < n; i++) {
int index = (int) (1.0 * k / arr[i]);
// If k is not power of two
if (index >= 0
&& ((index - (int)(index)) == 0)
&& mp.ContainsKey(k / arr[i])
&& (index != arr[i])) {
count += mp[arr[i]] * mp[index];
// After counting erase the element
mp.Remove(arr[i]);
mp.Remove(index);
}
// If k is power of 2
if (index >= 0
&& ((index - (int)(index)) == 0)
&& mp.ContainsKey(k / arr[i])
&& (index == arr[i])) {
// Pair count
count += (mp[arr[i]]
* (mp[arr[i]] - 1))
/ 2;
// After counting erase the element;
mp.Remove(arr[i]);
}
}
return count;
}
// Driver Code
public static void Main(String[] args)
{
int []arr = { 1, 2, 16, 4, 4, 4, 8 };
int N = arr.Length;
int K = 16;
Console.Write(countPairsWithProductK(arr, N, K));
}
}
// This code is contributed by Rajput-Ji
JavaScript
<script>
// JavaScript code for the above approach
// Function to count
// the total number of pairs
function countPairsWithProductK(
arr, n, k) {
let count = 0;
// Initialize hashmap.
let mp = new Map();
// Insert array elements to hashmap
for (let i = 0; i < n; i++) {
if (mp.has(arr[i])) {
mp.set(arr[i], mp.get(arr[i]) + 1);
}
else {
mp.set(arr[i], 1);
}
}
for (let i = 0; i < n; i++) {
let index = 1.0 * k / arr[i];
// If k is not power of two
if (index >= 0
&& ((index - Math.floor(index)) == 0)
&& mp.has(k / arr[i])
&& (index != arr[i])) {
count += mp.get(arr[i]) * mp.get(index);
// After counting erase the element
mp.delete(arr[i]);
mp.delete(index);
}
// If k is power of 2
if (index >= 0
&& ((index - Math.floor(index)) == 0)
&& mp.has(k / arr[i])
&& (index == arr[i])) {
// Pair count
count += (mp.get(arr[i])
* (mp.get(arr[i]) - 1))
/ 2;
// After counting erase the element;
mp.delete(arr[i]);
}
}
return count;
}
// Driver Code
let arr = [1, 2, 16, 4, 4, 4, 8];
let N = arr.length;
let K = 16;
document.write(countPairsWithProductK(arr, N, K));
// This code is contributed by Potta Lokesh
</script>
Time Complexity: O(N)
Auxiliary Space: O(N)
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem