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 Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Count of index pairs with equal elements in an array | Set 2
Next article icon

Count of elements A[i] such that A[i] + 1 is also present in the Array

Last Updated : 14 Sep, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

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: arr = [1, 1, 3, 3, 5, 5, 7, 7] 
Output: 0 
 

 

Approach 1: Brute Force Solution 
For all the elements in the array, return the total count after examining all elements 
 

  • For current element x, compute x + 1, and search all positions before and after the current value for x + 1.
  • If you find x + 1, add 1 to the total count

Below is the implementation of the above approach:
 

C++




// C++ program to count of elements
// A[i] such that A[i] + 1
// is also present in the Array
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the countElements
int countElements(int* arr, int n)
{
    // Initialize count as zero
    int count = 0;
 
    // Iterate over each element
    for (int i = 0; i < n; i++) {
 
        // Store element in int x
        int x = arr[i];
 
        // Calculate x + 1
        int xPlusOne = x + 1;
 
        // Initialize found as false
        bool found = false;
 
        // Run loop to search for x + 1
        // after the current element
        for (int j = i + 1; j < n; j++) {
            if (arr[j] == xPlusOne) {
                found = true;
                break;
            }
        }
 
        // Run loop to search for x + 1
        // before the current element
        for (int k = i - 1;
             !found && k >= 0; k--) {
            if (arr[k] == xPlusOne) {
                found = true;
                break;
            }
        }
 
        // if found is true, increment count
        if (found == true) {
            count++;
        }
    }
 
    return count;
}
 
// Driver program
int main()
{
    int arr[] = { 1, 2, 3 };
    int n = sizeof(arr) / sizeof(arr[0]);
 
    // call countElements function on array
    cout << countElements(arr, n);
 
    return 0;
}
 
 

Java




// Java program to count of elements
// A[i] such that A[i] + 1
// is also present in the Array
import java.io.*;
import java.util.Arrays;
 
class GFG{
     
// Function to find the countElements
public static int countElements(int[] arr, int n)
{
     
    // Initialize count as zero
    int count = 0;
     
    // Iterate over each element
    for (int i = 0; i < n; i++)
    {
     
        // Store element in int x
        int x = arr[i];
     
        // Calculate x + 1
        int xPlusOne = x + 1;
     
        // Initialize found as false
        boolean found = false;
     
        // Run loop to search for x + 1
        // after the current element
        for (int j = i + 1; j < n; j++)
        {
            if (arr[j] == xPlusOne)
            {
                found = true;
                break;
            }
        }
     
        // Run loop to search for x + 1
        // before the current element
        for (int k = i - 1; !found && k >= 0; k--)
        {
            if (arr[k] == xPlusOne)
            {
                found = true;
                break;
            }
        }
     
        // If found is true, increment count
        if (found == true)
        {
            count++;
        }
    }
        return count;
}
     
// Driver code
public static void main (String[] args)
{
    int arr[] = { 1, 2, 3 };
    int n = arr.length;
     
    // Call countElements function on array
    System.out.println(countElements(arr, n));
}
}
 
//This code is contributed by shubhamsingh10
 
 

Python3




# Python3 program to count of elements
# A[i] such that A[i] + 1
# is also present in the Array
 
# Function to find the countElements
def countElements(arr,n):
    # Initialize count as zero
    count = 0
 
    # Iterate over each element
    for i in range(n):
 
        # Store element in int x
        x = arr[i]
 
        # Calculate x + 1
        xPlusOne = x + 1
 
        # Initialize found as false
        found = False
 
        # Run loop to search for x + 1
        # after the current element
        for j in range(i + 1,n,1):
            if (arr[j] == xPlusOne):
                found = True
                break
 
        # Run loop to search for x + 1
        # before the current element
        k = i - 1
        while(found == False and k >= 0):
            if (arr[k] == xPlusOne):
                found = True
                break
            k -= 1
 
        # if found is true, increment count
        if (found == True):
            count += 1
 
    return count
 
# Driver program
if __name__ == '__main__':
    arr = [1, 2, 3]
    n = len(arr)
 
    # call countElements function on array
    print(countElements(arr, n))
 
# This code is contributed by Surendra_Gangwar
 
 

C#




// C# program to count of elements
// A[i] such that A[i] + 1
// is also present in the Array
using System;
 
class GFG{
     
    // Function to find the countElements
    static int countElements(int[] arr, int n)
    {
        // Initialize count as zero
        int count = 0;
     
        // Iterate over each element
        for (int i = 0; i < n; i++) {
     
            // Store element in int x
            int x = arr[i];
     
            // Calculate x + 1
            int xPlusOne = x + 1;
     
            // Initialize found as false
            bool found = false;
     
            // Run loop to search for x + 1
            // after the current element
            for (int j = i + 1; j < n; j++) {
                if (arr[j] == xPlusOne) {
                    found = true;
                    break;
                }
            }
     
            // Run loop to search for x + 1
            // before the current element
            for (int k = i - 1;
                !found && k >= 0; k--) {
                if (arr[k] == xPlusOne) {
                    found = true;
                    break;
                }
            }
     
            // if found is true,
            // increment count
            if (found == true) {
                count++;
            }
        }
     
        return count;
    }
     
    // Driver program
    static public void Main ()
    {
        int[] arr = { 1, 2, 3 };
        int n = arr.Length;
     
        // call countElements function on array
        Console.WriteLine(countElements(arr, n));
 
    }
}
 
// This code is contributed by shubhamsingh10
 
 

Javascript




<script>
// JavaScript program to count of elements
// A[i] such that A[i] + 1
// is also present in the Array
 
// Function to find the countElements
function countElements(arr, n)
{
    // Initialize count as zero
    let count = 0;
 
    // Iterate over each element
    for (let i = 0; i < n; i++) {
 
        // Store element in int x
        let x = arr[i];
 
        // Calculate x + 1
        let xPlusOne = x + 1;
 
        // Initialize found as false
        let found = false;
 
        // Run loop to search for x + 1
        // after the current element
        for (let j = i + 1; j < n; j++)
        {
            if (arr[j] == xPlusOne)
            {
                found = true;
                break;
            }
        }
 
        // Run loop to search for x + 1
        // before the current element
        for (let k = i - 1;
            !found && k >= 0; k--) {
            if (arr[k] == xPlusOne) {
                found = true;
                break;
            }
        }
 
        // if found is true, increment count
        if (found == true) {
            count++;
        }
    }
    return count;
}
 
// Driver program
    let arr = [ 1, 2, 3 ];
    let n = arr.length;
 
    // call countElements function on array
    document.write(countElements(arr, n));
 
// This code is contributed by Surbhi Tyagi.
</script>
 
 
Output: 
2

 

Time Complexity: In the above approach, for a given element, we check all other elements, So the time complexity is O(N*N) where N is no of elements. 
Auxiliary Space Complexity: In the above approach, we are not using any additional space, so Auxiliary space complexity is O(1).
Approach 2: Using Map 
 

  • For all elements in the array, say x, add x-1 to the map
  • Again, for all elements in the array, say x, check if it exists in the map. If it exists, increment the counter
  • Return the total count after examining all keys in the map

Below is the implementation of the above approach: 
 

C++




// C++ program to count of elements
// A[i] such that A[i] + 1
// is also present in the Array
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the countElements
int countElements(vector<int>& arr)
{
    int size = arr.size();
 
    // Initialize result as zero
    int res = 0;
 
    // Create map
    map<int, bool> dat;
 
    // First loop to fill the map
    for (int i = 0; i < size; ++i) {
        dat[arr[i] - 1] = true;
    }
 
    // Second loop to check the map
    for (int i = 0; i < size; ++i) {
        if (dat[arr[i]] == true) {
            res++;
        }
    }
    return res;
}
 
// Driver program
int main()
{
    // Input Array
    vector<int> arr = { 1, 3, 2, 3, 5, 0 };
 
    // Call the countElements function
    cout << countElements(arr) << endl;
 
    return 0;
}
 
 

Java




// Java program to count of elements
// A[i] such that A[i] + 1 is 
// also present in the Array
import java.util.*;
 
class GFG{
     
// Function to find the countElements
public static int countElements(int[] arr)
{
    int size = arr.length;
     
    // Initialize result as zero
    int res = 0;
     
    // Create map
    Map<Integer, Boolean> dat = new HashMap<>();
     
    // First loop to fill the map
    for(int i = 0; i < size; ++i)
    {
       dat.put((arr[i] - 1), true);
    }
     
    // Second loop to check the map
    for(int i = 0; i < size; ++i)
    {
       if (dat.containsKey(arr[i]) == true)
       {
           res++;
       }
    }
    return res;
}
     
// Driver code
public static void main(String[] args)
{
         
    // Input Array
    int[] arr = { 1, 3, 2, 3, 5, 0 };
     
    // Call the countElements function
    System.out.println(countElements(arr));
     
}
}
 
// This code is contributed by shad0w1947
 
 

Python3




# Python program to count of elements
# A[i] such that A[i] + 1
# is also present in the Array
 
# Function to find the countElements
def countElements(arr):
     
    size = len(arr)
     
    # Initialize result as zero
    res = 0
     
    # Create map
    dat={}
     
    # First loop to fill the map
    for i in range(size):
        dat[arr[i] - 1] = True
         
    # Second loop to check the map
    for i in range(size):
        if (arr[i] in dat):
            res += 1
     
    return res
 
# Driver program
 
# Input Array
arr =  [1, 3, 2, 3, 5, 0]
 
# Call the countElements function
print(countElements(arr))
 
# This code is contributed by shubhamsingh10
 
 

C#




// C# program to count of elements
// A[i] such that A[i] + 1 is
// also present in the Array
using System;
using System.Collections.Generic;
class GFG{
     
// Function to find the countElements
public static int countElements(int[] arr)
{
    int size = arr.Length;
     
    // Initialize result as zero
    int res = 0;
     
    // Create map
    Dictionary<int,
               Boolean> dat = new Dictionary<int,
                                             Boolean>();
     
    // First loop to fill the map
    for(int i = 0; i < size; ++i)
    {
       if(!dat.ContainsKey(arr[i] - 1))
          dat.Add((arr[i] - 1), true);
    }
     
    // Second loop to check the map
    for(int i = 0; i < size; ++i)
    {
       if (dat.ContainsKey(arr[i]) == true)
       {
           res++;
       }
    }
    return res;
}
     
// Driver code
public static void Main(String[] args)
{
         
    // Input Array
    int[] arr = { 1, 3, 2, 3, 5, 0 };
     
    // Call the countElements function
    Console.WriteLine(countElements(arr));
}
}
 
// This code is contributed by 29AjayKumar
 
 

Javascript




<script>
// javascript program to count of elements
// A[i] such that A[i] + 1 is 
// also present in the Array
 
    // Function to find the countElements
    function countElements(arr) {
        var size = arr.length;
 
        // Initialize result as zero
        var res = 0;
 
        // Create map
        var dat = new Map();
 
        // First loop to fill the map
        for (i = 0; i < size; ++i) {
            dat.set((arr[i] - 1), true);
        }
 
        // Second loop to check the map
        for (i = 0; i < size; ++i) {
            if (dat.has(arr[i]) == true) {
                res++;
            }
        }
        return res;
    }
 
        // Input Array
        var arr = [ 1, 3, 2, 3, 5, 0 ];
 
        // Call the countElements function
        document.write(countElements(arr));
 
// This code is contributed by umadevi9616
</script>
 
 
Output: 
3

 

Time Complexity: In the above approach, we iterate over the array twice. Once for filling the map and second time for checking the elements in the map, So the time complexity is O(N) where N is no of elements. 
Auxiliary Space Complexity: In the above approach, we are using an additional map which can contain N elements, so auxiliary space complexity is O(N).
 



Next Article
Count of index pairs with equal elements in an array | Set 2
author
coder001
Improve
Article Tags :
  • Algorithms
  • Arrays
  • DSA
  • School Programming
  • cpp-map
Practice Tags :
  • Algorithms
  • Arrays

Similar Reads

  • Count 1s present in a range of indices [L, R] in a given array
    Given an array arr[] consisting of a single element N (1 ≤ N ≤ 106) and two integers L and R, ( 1 ≤ L ≤ R ≤ 105), the task is to make all array elements either 0 or 1 using the following operations : Select an element P such that P > 1 from the array arr[].Replace P with three elements at the sam
    10 min read
  • 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
  • Count of index pairs with equal elements in an array | Set 2
    Given an array arr[] of N elements. The task is to count the total number of indices (i, j) such that arr[i] = arr[j] and i != j Examples: Input: arr[]={1, 2, 1, 1}Output: 3 Explanation:In the array arr[0]=arr[2]=arr[3]Valid Pairs are (0, 2), (0, 3) and (2, 3) Input: arr[]={2, 2, 3, 2, 3}Output: 4Ex
    8 min read
  • Count of pairs (arr[i], arr[j]) such that arr[i] + j and arr[j] + i are equal
    Given an array arr[], the task is to count pairs i, j such that, i < j and arr[i] + j = arr[j] + i. Examples: Input: arr[] = {4, 1, 2, 3}Output: 3Explanation: In total three pairs are satisfying the given condition those are {1, 2}, {2, 3} and {1, 3}.So, the final answer is 3. Input: arr[] = {1,
    5 min read
  • Count of all possible Arrays such that each array element can be over the range [1, arr[i]]
    Given an array arr[] consisting of N positive integers, the task is to find the number of all possible arrays such that each array element can be over the range [1, arr[i]] all elements in the newly constructed array must be pairwise distinct. Examples: Input: arr[] = {5}Output: 5Explanation:All pos
    5 min read
  • Count pairs in an array such that both elements has equal set bits
    Given an array arr [] of size N with unique elements, the task is to count the total number of pairs of elements that have equal set bits count. Examples: Input: arr[] = {2, 5, 8, 1, 3} Output: 4 Set bits counts for {2, 5, 8, 1, 3} are {1, 2, 1, 1, 2} All pairs with same set bits count are {2, 8}, {
    6 min read
  • 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
  • Count number of pairs (i, j) from an array such that arr[i] * j = arr[j] * i
    Given an array arr[] of size N, the task is to count the number of pairs (i, j) possible from the array such that arr[j] * i = arr[i] * j, where 1 ≤ i < j ≤ N. Examples: Input: arr[] = {1, 3, 5, 6, 5}Output: 2Explanation: Pair (1, 5) satisfies the condition, since arr[1] * 5 = arr[5] * 1.Pair (2,
    9 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 the divisors or multiples present in the Array for each element
    Given an array A[] with N integers, for each integer A[i] in the array, the task is to find the number of integers A[j] (j != i) in the array such that A[i] % A[j] = 0 or A[j] % A[i] = 0. Examples: Input: A = {2, 3, 4, 5, 6}Output: 2 1 1 0 2Explanation: For i=0, the valid indices are 2 and 4 as 4%2
    8 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