Count of pairs of elements with Sum X and multiplication Y in given Array
Last Updated :
23 Jul, 2025
Given array A[] (-109 <= A[i] <= 109) of size N (2 <= N <= 107) along with integers X (-2*109 <= X <= 2*109) and Y (-1018 <= Y <= 1018), the task for this problem is to find the count of pairs (A[i], A[j]) such that X = A[i] + A[j] and Y = A[i] * A[j] also i < j. Also A[i], X, Y != 0
Examples:
Input: A[] = {1, 4, -2, 3, 3, 3}, X = 7, Y = 12
Output: 3
Explanation: pairs (A[2], A[4]) = (4, 3), (A[2], A[5]) = (4, 3), and (A[2], A[6]) = (4, 3) are the pairs which satisfy above conditions.
Input: A[] = {1, 3, 2}, X = 5, Y = 6
Output: 1
Explanation: There is only one pair (A[2], A[3]) = (3, 2) which satisfy above conditions (X = A[2] + A[3] = 5 and Y = A[2] * A[3] = 6).
Naïve Approach: The basic way to solve the problem is as follows:
Simply iterating with two loops and maintaining a counter of pairs which satisfy above conditions.
Time Complexity: O(N2)
Auxiliary Space: O(1)
Efficient Approach: To solve the problem follow the below idea:
If X = A[i] + A[j] and Y = A[i] * A[j] then a2 - Xa + Y = 0 which is Quadratic equation in terms of sum and product of roots.
Here roots are A[i] and A[j]. so we just have to find the count of roots of quadratic equation in array A[] their multiplication will be answer. If the roots are integers then only its possible to find them in array otherwise answer will be zero. Here root will be (X + sqrt(Discriminant)) / 2 and (X - sqrt(Discriminant)) / 2 where Discriminant = X * X - 4 * Y.
Below are the steps for the above approach:
- Creating Variable for discriminant and calculate it.
- Check condition whether roots are integers or not. if not integer return 0.
- Find both the roots by above formula.
- If Discriminant is zero then there will be only one unique root find its count as cntRoot in array A[] and return answer: cntRoot * (cntRoot - 1) / 2.
- If Discriminant is not zero then find count of both the roots as firstRootCnt and secondRootCnt then return answer as : firstRootCnt * secondRootCnt.
Below is the implementation of the above approach:
C++
// C++ code to implement the approach
#include <bits/stdc++.h>
using namespace std;
// Function will tell whether given
// number is perfect square or not
bool isPerfectSquare(int number)
{
return sqrt(number) * sqrt(number) == number;
}
// Function to find count of pairs of integers
// with Sum X and multiplication Y
int findPairCount(int A[], int N, int X, int Y)
{
// Creating Variable for discriminant
int discriminant = X * X - 4 * Y;
// Check if both the roots are
// integers or not
if (isPerfectSquare(discriminant)
and (X + (int)sqrt(discriminant)) % 2 == 0
and (X - (int)sqrt(discriminant)) % 2 == 0) {
// First and second root
int firstRoot = (X + sqrt(discriminant)) / 2;
int secondRoot = (X - sqrt(discriminant)) / 2;
// If both roots are same that is
// discriminant is zero
if (discriminant == 0) {
// Variable that track count
// of cntRoot
int cntRoot = 0;
// Find count of given root
for (int i = 0; i < N; i++) {
if (A[i] == firstRoot)
cntRoot++;
}
// Answer in this case will be number
// of ways of choosing 2 elements
// from cntRoot
return cntRoot * (cntRoot - 1) / 2;
}
else {
// Find count of given roots
int firstRootCnt = 0, secondRootCnt = 0;
// Find count of given roots
for (int i = 0; i < N; i++) {
if (firstRoot == A[i])
firstRootCnt++;
else if (secondRoot == A[i])
secondRootCnt++;
}
// answer will be number of ways of
// choosing one element rom
// firstRootCnt and one element
// from second RootCnt;
return firstRootCnt * secondRootCnt;
}
}
// If roots are not interger then return 0
else {
return 0;
}
}
// Driver Code
int32_t main()
{
// Input 1
int X = 7, Y = 12;
int A[] = { 1, 4, -2, 3, 3, 3 }, N = 6;
// Function Call
cout << findPairCount(A, N, X, Y) << endl;
// Input 2
int X1 = 5, Y1 = 6;
int A1[] = { 1, 3, 2 }, N1 = 3;
// Function Call
cout << findPairCount(A1, N1, X1, Y1) << endl;
return 0;
}
Java
import java.util.Arrays;
public class Solution {
// Function will tell whether given number is a perfect square or not
static boolean isPerfectSquare(int number) {
int sqrt = (int) Math.sqrt(number);
return sqrt * sqrt == number;
}
// Function to find the count of pairs of integers with Sum X and multiplication Y
static int findPairCount(int[] A, int N, int X, int Y) {
// Creating Variable for discriminant
int discriminant = X * X - 4 * Y;
// Check if both the roots are integers or not
if (isPerfectSquare(discriminant)
&& (X + (int) Math.sqrt(discriminant)) % 2 == 0
&& (X - (int) Math.sqrt(discriminant)) % 2 == 0) {
// First and second root
int firstRoot = (X + (int) Math.sqrt(discriminant)) / 2;
int secondRoot = (X - (int) Math.sqrt(discriminant)) / 2;
// If both roots are the same, that is discriminant is zero
if (discriminant == 0) {
// Variable that tracks the count of cntRoot
int cntRoot = 0;
// Find count of given root
for (int i = 0; i < N; i++) {
if (A[i] == firstRoot)
cntRoot++;
}
// Answer in this case will be the number of ways of choosing 2 elements from cntRoot
return cntRoot * (cntRoot - 1) / 2;
} else {
// Find count of given roots
int firstRootCnt = 0, secondRootCnt = 0;
// Find count of given roots
for (int i = 0; i < N; i++) {
if (firstRoot == A[i])
firstRootCnt++;
else if (secondRoot == A[i])
secondRootCnt++;
}
// Answer will be the number of ways of choosing one element from firstRootCnt and one element from secondRootCnt;
return firstRootCnt * secondRootCnt;
}
}
// If roots are not integers, then return 0
else {
return 0;
}
}
// Driver Code
public static void main(String[] args) {
// Input 1
int X = 7, Y = 12;
int[] A = {1, 4, -2, 3, 3, 3};
int N = 6;
// Function Call
System.out.println(findPairCount(A, N, X, Y));
// Input 2
int X1 = 5, Y1 = 6;
int[] A1 = {1, 3, 2};
int N1 = 3;
// Function Call
System.out.println(findPairCount(A1, N1, X1, Y1));
}
}
Python
# Function to check if a number is a perfect square
def isPerfectSquare(number):
root = int(number ** 0.5)
return root * root == number
# Function to find the count of pairs of integers
# with Sum X and multiplication Y
def findPairCount(A, N, X, Y):
# Creating a variable for the discriminant
discriminant = X * X - 4 * Y
# Check if both the roots are integers or not
if isPerfectSquare(discriminant):
root = int(discriminant ** 0.5)
if (X + root) % 2 == 0 and (X - root) % 2 == 0:
# First and second root
firstRoot = (X + root) // 2
secondRoot = (X - root) // 2
# If both roots are the same (discriminant is zero)
if discriminant == 0:
# Variable that tracks the count of cntRoot
cntRoot = 0
# Find the count of the given root
for i in range(N):
if A[i] == firstRoot:
cntRoot += 1
# Answer in this case will be the number
# of ways of choosing 2 elements from cntRoot
return cntRoot * (cntRoot - 1) // 2
else:
# Find the count of given roots
firstRootCnt = 0
secondRootCnt = 0
# Find count of given roots
for i in range(N):
if firstRoot == A[i]:
firstRootCnt += 1
elif secondRoot == A[i]:
secondRootCnt += 1
# Answer will be the number of ways of
# choosing one element from
# firstRootCnt and one element
# from secondRootCnt;
return firstRootCnt * secondRootCnt
# If roots are not integers, then return 0
return 0
# Driver Code
def main():
# Input 1
X = 7
Y = 12
A = [1, 4, -2, 3, 3, 3]
N = 6
# Function Call
print(findPairCount(A, N, X, Y))
# Input 2
X1 = 5
Y1 = 6
A1 = [1, 3, 2]
N1 = 3
# Function Call
print(findPairCount(A1, N1, X1, Y1))
if __name__ == "__main__":
main()
C#
using System;
public class GFG
{
// Function will tell whether given number is a perfect square or not
static bool IsPerfectSquare(int number)
{
int sqrt = (int)Math.Sqrt(number);
return sqrt * sqrt == number;
}
// Function to find the count of pairs of integers with Sum X and multiplication Y
static int FindPairCount(int[] A, int N, int X, int Y)
{
// Creating Variable for discriminant
int discriminant = X * X - 4 * Y;
// Check if both the roots are integers or not
if (IsPerfectSquare(discriminant)
&& (X + (int)Math.Sqrt(discriminant)) % 2 == 0
&& (X - (int)Math.Sqrt(discriminant)) % 2 == 0)
{
// First and second root
int firstRoot = (X + (int)Math.Sqrt(discriminant)) / 2;
int secondRoot = (X - (int)Math.Sqrt(discriminant)) / 2;
// If both roots are the same, that is discriminant is zero
if (discriminant == 0)
{
// Variable that tracks the count of cntRoot
int cntRoot = 0;
// Find count of given root
for (int i = 0; i < N; i++)
{
if (A[i] == firstRoot)
cntRoot++;
}
// Answer in this case will be the number of ways of choosing 2 elements from cntRoot
return cntRoot * (cntRoot - 1) / 2;
}
else
{
// Find count of given roots
int firstRootCnt = 0, secondRootCnt = 0;
// Find count of given roots
for (int i = 0; i < N; i++)
{
if (firstRoot == A[i])
firstRootCnt++;
else if (secondRoot == A[i])
secondRootCnt++;
}
// Answer will be the number of ways of choosing one element from firstRootCnt and one element from secondRootCnt;
return firstRootCnt * secondRootCnt;
}
}
// If roots are not integers, then return 0
else
{
return 0;
}
}
// Driver Code
public static void Main(string[] args)
{
// Input 1
int X = 7, Y = 12;
int[] A = { 1, 4, -2, 3, 3, 3 };
int N = 6;
// Function Call
Console.WriteLine(FindPairCount(A, N, X, Y));
// Input 2
int X1 = 5, Y1 = 6;
int[] A1 = { 1, 3, 2 };
int N1 = 3;
// Function Call
Console.WriteLine(FindPairCount(A1, N1, X1, Y1));
}
}
JavaScript
function GFG(number) {
const sqrt = Math.sqrt(number);
return Math.floor(sqrt) * Math.floor(sqrt) === number;
}
// Function to find the count of pairs of integers with
// Sum X and multiplication Y
function Count(A, N, X, Y) {
// Creating a variable for the discriminant
const discriminant = X * X - 4 * Y;
// Check if both the roots are integers or not
if (GFG(discriminant)
&& (X + Math.sqrt(discriminant)) % 2 === 0
&& (X - Math.sqrt(discriminant)) % 2 === 0) {
// First and second root
const firstRoot = (X + Math.sqrt(discriminant)) / 2;
const secondRoot = (X - Math.sqrt(discriminant)) / 2;
// If both roots are the same
// that is discriminant is zero
if (discriminant === 0) {
// Variable that tracks the count of cntRoot
let cntRoot = 0;
// Find count of given root
for (let i = 0; i < N; i++) {
if (A[i] === firstRoot)
cntRoot++;
}
// Answer in this case will be the number of ways of
// choosing 2 elements from cntRoot
return (cntRoot * (cntRoot - 1)) / 2;
} else {
// Find count of given roots
let firstRootCnt = 0;
let secondRootCnt = 0;
// Find count of given roots
for (let i = 0; i < N; i++) {
if (firstRoot === A[i])
firstRootCnt++;
else if (secondRoot === A[i])
secondRootCnt++;
}
// Answer will be the number of ways of choosing one element from
// firstRootCnt and one element from secondRootCnt;
return firstRootCnt * secondRootCnt;
}
}
// If roots are not integers, then return 0
else {
return 0;
}
}
// Driver Code
// Input 1
const X = 7;
const Y = 12;
const A = [1, 4, -2, 3, 3, 3];
const N = 6;
// Function Call
console.log(Count(A, N, X, Y));
// Input 2
const X1 = 5;
const Y1 = 6;
const A1 = [1, 3, 2];
const N1 = 3;
// Function Call
console.log(Count(A1, N1, X1, Y1));
Time Complexity: O(N)
Auxiliary Space: O(1)
Related Articles:
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