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:
Count of elements such that its sum/difference with X also exists in the Array
Next article icon

Find the number of elements X such that X + K also exists in the array

Last Updated : 03 Jul, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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 = 2
Output: 5
Explanation:
Elements {3, 6, 7, 6, 5} in this array have x + 2 value that is
{5, 8, 9, 8, 7} present in this array.
Input: { 1, 2, 3, 4, 5} and k = 1
Output: 4
Explanation:
Elements {1, 2, 3, 4} in this array have x + 2 value that is
{2, 3, 4, 5} present in this array.

The problem is similar to finding the count of pairs with a given sum in an Array.

Brute Force Approach:
 

  1. Initialize a counter variable to 0 to keep track of the number of elements that satisfy the given condition.
  2. Use nested loops to iterate over all possible pairs of elements in the array.
  3. For each pair, check if their sum is equal to k plus any element in the array. If it is, increment the counter by 1.
  4. After all pairs have been checked, return the counter variable as the output.

Below is the implementation of the above approach: 

C++




// C++ implementation of find number
// of elements x in this array
// such x+k also present in this array.
#include <bits/stdc++.h>
using namespace std;
 
// Function to return the
// count of element x such that
// x+k also lies in this array
int count_element(int N, int K, int* arr)
{
    int count = 0;
    for(int i=0; i<N; i++){
        for(int j=0; j<N; j++){
            if(arr[j] == arr[i] + K){
                count++;
                break;
            }
        }
    }
    return count;
}
 
 
// Driver code
int main()
{
    // array initialisation
    int arr[] = { 3, 6, 2, 8, 7, 6, 5, 9 };
 
    // size of array
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // initialise k
    int K = 2;
    cout << count_element(N, K, arr);
 
    return 0;
}
 
 

Java




import java.util.Arrays;
 
public class Main {
    // Function to return the count of element x such that x+k also lies in this array
    public static int count_element(int N, int K, int[] arr) {
        int count = 0;
        for (int i = 0; i < N; i++) {
            for (int j = 0; j < N; j++) {
                if (arr[j] == arr[i] + K) {
                    count++;
                    break;
                }
            }
        }
        return count;
    }
 
    // Driver code
    public static void main(String[] args) {
        // array initialization
        int[] arr = {3, 6, 2, 8, 7, 6, 5, 9};
 
        // size of array
        int N = arr.length;
 
        // initialize k
        int K = 2;
        System.out.println(count_element(N, K, arr));
    }
}
 
 

Python3




# Python3 implementation of find number
# of elements x in this array
# such x+k also present in this array.
 
# array initialization
arr = [3, 6, 2, 8, 7, 6, 5, 9]
 
# Function to return the count of element x such that
# x+k also lies in this array
 
 
def count_element(N: int, K: int, arr: list) -> int:
    count = 0
    for i in range(N):
        for j in range(N):
            if arr[j] == arr[i] + K:
                count += 1
                break
    return count
 
 
# size of array
N = len(arr)
 
# initialize k
K = 2
 
print(count_element(N, K, arr))
 
 

C#




using System;
 
class GFG
{
    // Function to return the count of element x
   // such that x+k also lies in this array
    public static int count_element(int N, int K, int[] arr)
    {
        int count = 0;
        for (int i = 0; i < N; i++)
        {
            for (int j = 0; j < N; j++)
            {
                if (arr[j] == arr[i] + K)
                {
                    count++;
                    break;
                }
            }
        }
        return count;
    }
 
    // Driver code
    public static void Main(string[] args)
    {
        // array initialization
        int[] arr = { 3, 6, 2, 8, 7, 6, 5, 9 };
 
        // size of array
        int N = arr.Length;
 
        // initialize k
        int K = 2;
        Console.WriteLine(count_element(N, K, arr));
    }
}
 
// Contributed by phasing17
 
 

Javascript




// Function to return the
// count of element x such that
// x+k also lies in this array
function count_element(N, K, arr) {
  let count = 0;
  for(let i=0; i<N; i++){
      for(let j=0; j<N; j++){
          if(arr[j] == arr[i] + K){
              count++;
              break;
          }
      }
  }
  return count;
}
 
// Driver code
const arr = [3, 6, 2, 8, 7, 6, 5, 9];
 
// size of array
const N = arr.length;
 
// initialise k
const K = 2;
console.log(count_element(N, K, arr));
 
//This code is written by Sundaram
 
 
Output
5  

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

Efficient Approach:
The efficient approach to solve the problem is to use a HashMap, the key in map will act as the unique element in this array and the corresponding value will tell us the frequency of this element. 
Iterate over this map and find for each key x in this map whether the key x + k exists in the map or not, if exist then add this frequency to the answer i.e for this element x we have x+k in this array. Finally, return the answer.
Below is the implementation of the above approach: 
 

C++




// C++ implementation of find number
// of elements x in this array
// such x+k also present in this array.
#include <bits/stdc++.h>
using namespace std;
 
// Function to return the
// count of element x such that
// x+k also lies in this array
int count_element(int N, int K, int* arr)
{
    // Key in map will store elements
    // and value will store the
    // frequency of the elements
    map<int, int> mp;
 
    for (int i = 0; i < N; ++i)
        mp[arr[i]]++;
 
    int answer = 0;
 
    for (auto i : mp) {
 
        // Find if i.first + K is
        // present in this map or not
        if (mp.find(i.first + K) != mp.end())
 
            // If we find i.first or key + K in this map
            // then we have to increase in answer
            // the frequency of this element
            answer += i.second;
    }
 
    return answer;
}
 
// Driver code
int main()
{
    // array initialisation
    int arr[] = { 3, 6, 2, 8, 7, 6, 5, 9 };
 
    // size of array
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // initialise k
    int K = 2;
 
    cout << count_element(N, K, arr);
 
    return 0;
}
 
 

Java




// Java implementation of find number
// of elements x in this array
// such x+k also present in this array.
import java.util.*;
 
class GFG{
  
// Function to return the
// count of element x such that
// x+k also lies in this array
static int count_element(int N, int K, int[] arr)
{
    // Key in map will store elements
    // and value will store the
    // frequency of the elements
    HashMap<Integer,Integer> mp = new HashMap<Integer,Integer>();
  
    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);
    }
  
    int answer = 0;
  
    for (Map.Entry<Integer,Integer> i : mp.entrySet()) {
  
        // Find if i.first + K is
        // present in this map or not
        if (mp.containsKey(i.getKey() + K) )
  
            // If we find i.first or key + K in this map
            // then we have to increase in answer
            // the frequency of this element
            answer += i.getValue();
    }
  
    return answer;
}
  
// Driver code
public static void main(String[] args)
{
    // array initialisation
    int arr[] = { 3, 6, 2, 8, 7, 6, 5, 9 };
  
    // size of array
    int N = arr.length;
  
    // initialise k
    int K = 2;
  
    System.out.print(count_element(N, K, arr));
}
}
 
// This code is contributed by Princi Singh
 
 

Python3




# Python3 implementation of find number
# of elements x in this array
# such x+k also present in this array.
 
# Function to return the
# count of element x such that
# x+k also lies in this array
def count_element(N, K, arr):
     
    # Key in map will store elements
    # and value will store the
    # frequency of the elements
    mp = dict()
 
    for i in range(N):
        mp[arr[i]] = mp.get(arr[i], 0) + 1
 
    answer = 0
 
    for i in mp:
 
        # Find if i.first + K is
        # present in this map or not
        if i + K in mp:
 
            # If we find i.first or key + K in this map
            # then we have to increase in answer
            # the frequency of this element
            answer += mp[i]
 
    return answer
 
# Driver code
if __name__ == '__main__':
    # array initialisation
    arr=[3, 6, 2, 8, 7, 6, 5, 9]
 
    # size of array
    N = len(arr)
 
    # initialise k
    K = 2
 
    print(count_element(N, K, arr))
     
# This code is contributed by mohit kumar 29   
 
 

C#




// C# implementation of find number
// of elements x in this array
// such x+k also present in this array.
using System;
using System.Collections.Generic;
 
public class GFG{
   
// Function to return the
// count of element x such that
// x+k also lies in this array
static int count_element(int N, int K, int[] arr)
{
    // Key in map will store elements
    // and value will store the
    // frequency of the elements
    Dictionary<int,int> mp = new Dictionary<int,int>();
   
    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);
    }
   
    int answer = 0;
   
    foreach (KeyValuePair<int,int> i in mp) {
   
        // Find if i.first + K is
        // present in this map or not
        if (mp.ContainsKey(i.Key + K) )
   
            // If we find i.first or key + K in this map
            // then we have to increase in answer
            // the frequency of this element
            answer += i.Value;
    }
   
    return answer;
}
   
// Driver code
public static void Main(String[] args)
{
    // array initialisation
    int []arr = { 3, 6, 2, 8, 7, 6, 5, 9 };
   
    // size of array
    int N = arr.Length;
   
    // initialise k
    int K = 2;
   
    Console.Write(count_element(N, K, arr));
}
}
// This code contributed by Princi Singh
 
 

Javascript




<script>
// Javascript implementation of find number
// of elements x in this array
// such x+k also present in this array.
 
 
// Function to return the
// count of element x such that
// x+k also lies in this array
function count_element(N, K, arr)
{
 
    // Key in map will store elements
    // and value will store the
    // frequency of the elements
    let mp = new Map();
 
    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)
        }
 
    let answer = 0;
 
    for (let i of mp) {
 
        // Find if i.first + K is
        // present in this map or not
        if (mp.has(i[0] + K))
 
            // If we find i.first or key + K in this map
            // then we have to increase in answer
            // the frequency of this element
            answer += i[1];
    }
 
    return answer;
}
 
// Driver code
 
// array initialisation
let arr = [3, 6, 2, 8, 7, 6, 5, 9];
 
// size of array
let N = arr.length;
 
// initialise k
let K = 2;
 
document.write(count_element(N, K, arr));
 
// This code is contributed by gfgking
</script>
 
 
Output
5  

Time Complexity: O(N log N), where N is the size of the input array

Space Complexity: O(N)



Next Article
Count of elements such that its sum/difference with X also exists in the Array
author
shivamsinghal1012
Improve
Article Tags :
  • Algorithms
  • Arrays
  • DSA
  • Greedy
  • Hash
Practice Tags :
  • Algorithms
  • Arrays
  • Greedy
  • Hash

Similar Reads

  • Count of elements such that its sum/difference with X also exists in the Array
    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 -
    9 min read
  • Find the number of elements greater than k in a sorted array
    Given a sorted array arr[] of integers and an integer k, the task is to find the count of elements in the array which are greater than k. Note that k may or may not be present in the array.Examples: Input: arr[] = {2, 3, 5, 6, 6, 9}, k = 6 Output: 1Input: arr[] = {1, 1, 2, 5, 5, 7}, k = 8 Output: 0
    7 min read
  • Find X such that most Array elements are of form (X + p*K)
    Given an array arr[] and a number K, the task is to find a value X such that maximum number of array elements can be expressed in the form (X + p*K). Note: If there are multiple possible values of X, print the minimum among them. Examples: Input: arr[] = {1, 3, 5, 2, 4, 6}, k = 2Output: 1Explanation
    11 min read
  • Number of ways to choose elements from the array such that their average is K
    Given an array arr[] of N integers and an integer K. The task is to find the number of ways to select one or more elements from the array such that the average of the selected integers is equal to the given number K. Examples: Input: arr[] = {7, 9, 8, 9}, K = 8 Output: 5 {8}, {7, 9}, {7, 9}, {7, 8,
    11 min read
  • Find a number K such that exactly K array elements are greater than or equal to K
    Given an array a[] of size N, which contains only non-negative elements, the task is to find any integer K for which there are exactly K array elements that are greater than or equal to K. If no such K exists, then print -1. Examples: Input: a[] = {7, 8, 9, 0, 0, 1}Output: 3Explanation:Since 3 is le
    10 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
  • Queries for number of array elements in a range with Kth Bit Set
    Given an array of N positive (32-bit)integers, the task is to answer Q queries of the following form: Query(L, R, K): Print the number of elements of the array in the range L to R, which have their Kth bit as set Note: Consider LSB to be indexed at 1. Examples: Input : arr[] = { 8, 9, 1, 3 } Query 1
    15+ min read
  • Given Array of size n and a number k, find all elements that appear more than n/k times
    Given an array of size n and an integer k, find all elements in the array that appear more than n/k times. Examples: Input: arr[ ] = [3, 4, 2, 2, 1, 2, 3, 3], k = 4Output: [2, 3]Explanation: Here n/k is 8/4 = 2, therefore 2 appears 3 times in the array that is greater than 2 and 3 appears 3 times in
    15+ min read
  • Find the Kth occurrence of an element in a sorted Array
    Given a sorted array arr[] of size N, an integer X, and a positive integer K, the task is to find the index of Kth occurrence of X in the given array. Examples: Input: N = 10, arr[] = [1, 2, 3, 3, 4, 5, 5, 5, 5, 5], X = 5, K = 2Output: Starting index of the array is '0' Second occurrence of 5 is at
    15+ min read
  • Sum of all the elements in an array divisible by a given number K
    Given an array containing N elements and a number K. The task is to find the sum of all such elements which are divisible by K. Examples: Input : arr[] = {15, 16, 10, 9, 6, 7, 17} K = 3 Output : 30 Explanation: As 15, 9, 6 are divisible by 3. So, sum of elements divisible by K = 15 + 9 + 6 = 30. Inp
    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