Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on Hash
  • Practice Hash
  • MCQs on Hash
  • Hashing Tutorial
  • Hash Function
  • Index Mapping
  • Collision Resolution
  • Open Addressing
  • Separate Chaining
  • Quadratic probing
  • Double Hashing
  • Load Factor and Rehashing
  • Advantage & Disadvantage
Open In App
Next Article:
Find pair i, j such that |A[i]−A[j]| is same as sum of difference of them with any Array element
Next article icon

Count of elements such that its sum/difference with X also exists in the Array

Last Updated : 02 Oct, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array arr[] and an integer X, the task is to count the elements of the array such that their exist a element [Tex]arr[i] – X             [/Tex]or [Tex]arr[i] + X             [/Tex]in the array.
Examples:  

Input: arr[] = {3, 4, 2, 5}, X = 2 
Output: 4 
Explanation: 
In the above-given example, there are 4 such numbers – 
For Element 3: Possible numbers are 1, 5, whereas 5 is present in array 
For Element 4: Possible numbers are 2, 6, whereas 2 is present in array 
For Element 2: Possible numbers are 0, 4, whereas 4 is present in array 
For Element 5: Possible numbers are 3, 7, whereas 3 is present in array 
Therefore, Total count = 4
Input: arr[] = {2, 2, 4, 5, 6}, X = 3 
Output: 3 
Explanation: 
In the above-given example, there are 3 such numbers {2, 2, 5} 

Brute Force Approach:

  1. Initialize a variable count to 0 to keep track of the count of elements that satisfy the condition.
  2. Loop through each element ‘num’ in the array arr.
  3. For each element ‘num’, check if either ‘num + x’ or ‘num – x’ is present in the array arr.
  4. If either ‘num + x’ or ‘num – x’ is present in the array arr, increment the count variable.
  5. After looping through all elements in the array arr, return the value of count.

Below is the implementation of the above approach:

C++

// C++ implementation to count of
// elements such that its sum/difference
// with X also exists in the Array
 
#include <bits/stdc++.h>
 
using namespace std;
 
// Function to find the count of
// elements in the array such that
// element at the difference at X
// is present in the array
void findAns(int arr[], int n, int x)
{
    int count = 0;
    for(int i = 0; i < n; i++)
    {
        for(int j = 0; j < n; j++)
        {
            if(i != j && (arr[i] - arr[j] == x || arr[j] - arr[i] == x))
            {
                count++;
                break;
            }
        }
    }
    cout << count << endl;
}
 
 
// Driver Code
int main()
{
    int arr[] = { 2, 2, 4, 5, 6 };
    int n = sizeof(arr) / sizeof(int);
    int x = 3;
 
    findAns(arr, n, x);
 
    return 0;
}
                      
                       

Java

import java.util.*;
 
public class Main {
    // Function to find the count of elements in the array such that
    // element at the difference at X is present in the array
    public static void findAns(int[] arr, int n, int x) {
        int count = 0;
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                if (i != j && (arr[i] - arr[j] == x || arr[j] - arr[i] == x)) {
                    count++;
                    break;
                }
            }
        }
        System.out.println(count);
    }
 
    // Driver Code
    public static void main(String[] args) {
        int[] arr = {2, 2, 4, 5, 6};
        int n = arr.length;
        int x = 3;
 
        findAns(arr, n, x);
    }
}
                      
                       

Python3

def findAns(arr, n, x):
    # Function to find the count of elements in the array such that
    # element at the difference at X is present in the array
    count = 0
    for i in range(n):
        for j in range(n):
            if i != j and (arr[i] - arr[j] == x or arr[j] - arr[i] == x):
                count += 1
                break
    print(count)
 
# Driver code
if __name__ == '__main__':
    arr = [2, 2, 4, 5, 6]
    n = len(arr)
    x = 3
 
    findAns(arr, n, x)
                      
                       

C#

using System;
 
class Program
{
    // Function to find the count of elements in the array such that the
    // element's sum or difference with X exists in the array
    static void FindCount(int[] arr, int n, int x)
    {
        int count = 0;
        for (int i = 0; i < n; i++)
        {
            for (int j = 0; j < n; j++)
            {
                if (i != j && (arr[i] - arr[j] == x || arr[j] - arr[i] == x))
                {
                    count++;
                    break;
                }
            }
        }
        Console.WriteLine(count);
    }
 
    // Driver Code
    static void Main()
    {
        int[] arr = { 2, 2, 4, 5, 6 };
        int n = arr.Length;
        int x = 3;
 
        FindCount(arr, n, x);
    }
}
                      
                       

Javascript

function findAns(arr, N, x) {
    let count = 0;
    for (let i = 0; i < N; i++) {
        for (let j = 0; j < N; j++) {
            if (i !== j && (arr[i] - arr[j] === x || arr[j] - arr[i] === x)) {
                count++;
                break;
            }
        }
    }
    console.log(count);
}
// Driver Code
const arr = [2, 2, 4, 5, 6];
const N = arr.length;
const x = 3;
GFG(arr, N, x);
                      
                       

Output
3   

Time Complexity: O(N^2)
Auxiliary Space: O(1)

Approach: The idea is to use hash-map to check that an element is present in the hash-map or not in O(1) time. Then, iterate over the elements of the array and for each element check that [Tex]arr[i] – X             [/Tex]or [Tex]arr[i] + X             [/Tex]is present in the array. If yes, then increment the count of such elements by 1.
Below is the implementation of the above approach:
 

C++

// C++ implementation to count of
// elements such that its sum/difference
// with X also exists in the Array
 
#include <bits/stdc++.h>
 
using namespace std;
 
// Function to find the count of
// elements in the array such that
// element at the difference at X
// is present in the array
void findAns(int arr[], int n, int x)
{
    int ans;
    unordered_set<int> s;
 
    // Loop to insert the elements
    // of the array into the set
    for (int i = 0; i < n; i++)
        s.insert(arr[i]);
 
    ans = 0;
 
    // Loop to iterate over the array
    for (int i = 0; i < n; i++) {
 
        // if any of the elements are there
        // then increase the count variable
        if (s.find(arr[i] + x) != s.end() || s.find(arr[i] - x) != s.end())
            ans++;
    }
    cout << ans;
    return;
}
 
// Driver Code
int main()
{
    int arr[] = { 2, 2, 4, 5, 6 };
    int n = sizeof(arr) / sizeof(int);
    int x = 3;
 
    findAns(arr, n, x);
 
    return 0;
}
                      
                       

Java

// Java implementation to count of
// elements such that its sum/difference
// with X also exists in the Array
import java.util.*;
class GFG{
 
// Function to find the count of
// elements in the array such that
// element at the difference at X
// is present in the array
static void findAns(int arr[],
                    int n, int x)
{
    int ans;
    HashSet<Integer> s = new HashSet<Integer>();
 
    // Loop to insert the elements
    // of the array into the set
    for (int i = 0; i < n; i++)
        s.add(arr[i]);
 
    ans = 0;
 
    // Loop to iterate over the array
    for (int i = 0; i < n; i++)
    {
 
        // if any of the elements are there
        // then increase the count variable
        if (s.contains(arr[i] + x) ||
            s.contains(arr[i] - x))
            ans++;
    }
    System.out.print(ans);
    return;
}
 
// Driver Code
public static void main(String[] args)
{
    int arr[] = { 2, 2, 4, 5, 6 };
    int n = arr.length;
    int x = 3;
 
    findAns(arr, n, x);
}
}
 
// This code is contributed by Rajput-Ji
                      
                       

Python3

# Python3 implementation to count of
# elements such that its sum/difference
# with X also exists in the array
 
# Function to find the count of
# elements in the array such that
# element at the difference at X
# is present in the array
def findAns(arr, n, x):
     
    s = set()
     
    # Loop to insert the elements
    # of the array into the set
    for i in range(n):
        s.add(arr[i])
         
    ans = 0
 
    # Loop to iterate over the array
    for i in range(n):
         
        # If any of the elements are there
        # then increase the count variable
        if arr[i] + x in s or arr[i] - x in s:
            ans = ans + 1
 
    print(ans)
 
# Driver Code
arr = [ 2, 2, 4, 5, 6 ]
n = len(arr)
x = 3
 
# Function call
findAns(arr, n, x)
 
# This code is contributed by ishayadav181
                      
                       

C#

// C# implementation to count of
// elements such that its sum/difference
// with X also exists in the Array
using System;
using System.Collections.Generic;
 
class GFG{
 
// Function to find the count of
// elements in the array such that
// element at the difference at X
// is present in the array
static void findAns(int[] arr,
                    int n, int x)
{
    int ans;
    HashSet<int> s = new HashSet<int>();
     
    // Loop to insert the elements
    // of the array into the set
    for(int i = 0; i < n; i++)
       s.Add(arr[i]);
     
    ans = 0;
     
    // Loop to iterate over the array
    for(int i = 0; i < n; i++)
    {
        
       // if any of the elements are there
       // then increase the count variable
       if (s.Contains(arr[i] + x) ||
           s.Contains(arr[i] - x))
           ans++;
    }
    Console.Write(ans);
    return;
}
     
// Driver Code
public static void Main(String[] args)
{
    int[] arr = { 2, 2, 4, 5, 6 };
    int n = arr.Length;
    int x = 3;
     
    findAns(arr, n, x);
}
}
 
// This code is contributed by ShubhamCoder
                      
                       

Javascript

<script>
 
// Javascript implementation to count of
// elements such that its sum/difference
// with X also exists in the Array
 
// Function to find the count of
// elements in the array such that
// element at the difference at X
// is present in the array
function findAns(arr, n, x)
{
    let ans;
    let s = new Set();
   
    // Loop to insert the elements
    // of the array leto the set
    for (let i = 0; i < n; i++)
        s.add(arr[i]);
   
    ans = 0;
   
    // Loop to iterate over the array
    for (let i = 0; i < n; i++)
    {
   
        // if any of the elements are there
        // then increase the count variable
        if (s.has(arr[i] + x) ||
            s.has(arr[i] - x))
            ans++;
    }
    document.write(ans);
    return;
}
 
// Driver code
     
      let arr = [ 2, 2, 4, 5, 6 ];
    let n = arr.length;
    let x = 3;
   
    findAns(arr, n, x);
  
 // This code is contributed by code_hunt.
</script>
                      
                       

Output
3    

Performance Analysis: 
 

  • Time Complexity: O(N)
  • Auxiliary Space Complexity: O(N)


 



Next Article
Find pair i, j such that |A[i]−A[j]| is same as sum of difference of them with any Array element
author
papun007
Improve
Article Tags :
  • Arrays
  • Data Structures
  • DSA
  • Hash
  • School Programming
Practice Tags :
  • Arrays
  • Data Structures
  • Hash

Similar Reads

  • Find the number of elements X such that X + K also exists in the array
    Given an array a[] and an integer k, find the number of elements x in this array such that the sum of x and k is also present in the array. Examples: Input: { 3, 6, 2, 8, 7, 6, 5, 9 } and k = 2Output: 5 Explanation:Elements {3, 6, 7, 6, 5} in this array have x + 2 value that is{5, 8, 9, 8, 7} presen
    10 min read
  • Find pair i, j such that |A[i]−A[j]| is same as sum of difference of them with any Array element
    Given an array A[] having N non-negative integers, find a pair of indices i and j such that the absolute difference between them is same as the sum of differences of those with any other array element i.e., | A[i] − A[k] | + | A[k]− A[j] | = | A[i] − A[j] |, where k can be any index. Examples: Input
    7 min read
  • Count of elements whose absolute difference with the sum of all the other elements is greater than k
    Given an array arr[] of N integers and an integer K, the task is to find the number of anomalies in the array. An anomaly is a number for which the absolute difference between it and all the other numbers in the array is greater than K. Find the number of anomalies. Examples: Input: arr[] = {1, 3, 5
    5 min read
  • Count of elements A[i] such that A[i] + 1 is also present in the Array
    Given an integer array arr the task is to count the number of elements 'A[i]', such that A[i] + 1 is also present in the array.Note: If there are duplicates in the array, count them separately.Examples: Input: arr = [1, 2, 3] Output: 2 Explanation: 1 and 2 are counted cause 2 and 3 are in arr.Input:
    11 min read
  • Count of elements which is the sum of a subarray of the given Array
    Given an array arr[], the task is to count elements in an array such that there exists a subarray whose sum is equal to this element.Note: Length of subarray must be greater than 1. Examples: Input: arr[] = {1, 2, 3, 4, 5, 6, 7} Output: 4 Explanation: There are 4 such elements in array - arr[2] = 3
    7 min read
  • Count pairs in an array such that the absolute difference between them is ≥ K
    Given an array arr[] and an integer K, the task is to find the count of pairs (arr[i], arr[j]) from the array such that |arr[i] - arr[j]| ? K. Note that (arr[i], arr[j]) and arr[j], arr[i] will be counted only once.Examples: Input: arr[] = {1, 2, 3, 4}, K = 2 Output: 3 All valid pairs are (1, 3), (1
    6 min read
  • Array element with minimum sum of absolute differences | Set 2
    Given an array arr[] consisting of N positive integers, the task is to find an array element X such that sum of its absolute differences with every array element is minimum. Examples: Input: arr[] = {1, 2, 3, 4, 5}Output: 3Explanation: For element arr[0](= 1): |(1 - 1)| + |(2 - 1)| + |(3 - 1)| + |(4
    7 min read
  • Count elements in first Array with absolute difference greater than K with an element in second Array
    Given two arrays arr1[] and arr2[] and an integer K, our task is to find the number elements in the first array, for an element x, in arr1[], there exists at least one element y, in arr2[] such that absolute difference of x and y is greater than the integer K. Examples: Input: arr1 = {3, 1, 4}, arr2
    7 min read
  • Count of indices pairs such that product of elements at these indices is equal to absolute difference of indices
    Given an array arr[] consisting of N positive integers, the task is to find the number of pairs (i, j) such that i < j and the product of elements at these indices is equal to the absolute difference of their indices. Examples: Input: arr[] = {1, 1, 2, 4}Output: 2Explanation:Following are the pos
    10 min read
  • Count of distinct index pair (i, j) such that element sum of First Array is greater
    Given two arrays a[] and b[], both of size N. The task is to count the number of distinct pairs such that (a[i] + a[j] ) > ( b[i] + b[j] ) subject to condition that (j > i). Examples: Input: N = 5, a[] = {1, 2, 3, 4, 5}, b[] = {2, 5, 6, 1, 9} Output: 1 Explanation: Only one such pair exists an
    13 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences