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 pairs in an array having sum of elements with their respective sum of digits equal
Next article icon

Count of pairs having each element equal to index of the other from an Array

Last Updated : 25 Jan, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an integer N and an array arr[] that contains elements in the range [1, N], the task is to find the count of all pairs (arr[i], arr[j]) such that i < j and i == arr[j] and j == arr[i].

Examples:  

Input: N = 4, arr[] = {2, 1, 4, 3} 
Output: 2 
Explanation: 
All possible pairs are {1, 2} and {3, 4}

Input: N = 5, arr[] = {5, 5, 5, 5, 1} 
Output: 1 
Explanation: 
Only possible pair: {1, 5} 

Naive Approach: 
The simplest approach is to generate all possible pairs of the given array and if any pair satisfies the given condition, increase count. Finally, print the value of count. 

C++
// C++ program to implement // the above approach #include <bits/stdc++.h> using namespace std;  // Function to print the count of pair void countPairs(int N, int arr[]) {     int count = 0;      // Iterate over all the     // elements of the array     for (int i = 0; i < N - 1; i++) {         for (int j = i + 1; j < N; j++) {             if ((i + 1) == arr[j] && (j + 1) == arr[i])                 count++;         }     }      // Print the result     cout << count << endl; }  // Driver Code int main() {     int arr[] = { 5, 5, 5, 5, 1 };     int N = sizeof(arr) / sizeof(arr[0]);      countPairs(N, arr); } 
Java
import java.util.Arrays;  public class Gfg {     public static void main(String[] args)     {         int[] arr = { 5, 5, 5, 5, 1 };         int N = arr.length;         int count = 0;          // Iterate over all the         // elements of the array         for (int i = 0; i < N - 1; i++) {             for (int j = i + 1; j < N; j++) {                 if ((i + 1) == arr[j] && (j + 1) == arr[i])                     count++;             }         }         // Print the result         System.out.println(count);     } } 
Python3
def countPairs(N, arr):     count = 0     # Iterate over all the     # elements of the array     for i in range(N-1):         for j in range(i+1, N):             if (i + 1) == arr[j] and (j + 1) == arr[i]:                 count += 1      # Print the result     print(count)  # Driver code if __name__ == "__main__":     arr = [5, 5, 5, 5, 1]     N = len(arr)     countPairs(N, arr) 
C#
using System;  class Gfg {     public static void Main(string[] args)     {         int[] arr = { 5, 5, 5, 5, 1 };         int N = arr.Length;         int count = 0;          // Iterate over all the         // elements of the array         for (int i = 0; i < N - 1; i++)         {             for (int j = i + 1; j < N; j++)             {                 if ((i + 1) == arr[j] && (j + 1) == arr[i])                     count++;             }         }         // Print the result         Console.WriteLine(count);     } } 
JavaScript
// Javascript program to implement // the above approach  // Function to print the count of pair function countPairs(N, arr) {     let count = 0;      // Iterate over all the     // elements of the array     for (let i = 0; i < N - 1; i++) {         for (let j = i + 1; j < N; j++) {             if ((i + 1) == arr[j] && (j + 1) == arr[i])                 count++;         }     }      // Print the result     console.log(count); }  // Driver Code let arr = [ 5, 5, 5, 5, 1 ]; let N = arr.length;  countPairs(N, arr);  // This code is contributed by agrawalpoojaa976. 

Output
1

Time Complexity: O(N2) 
Auxiliary Space: O(1)

Efficient Approach: 
Follow the steps below to solve the above approach:  

  • Traverse the given array and keep the count of elements(say cnt) whose index equals to arr[arr[index] - 1] - 1. This will count the valid pair with the given criteria.
  • After traversal, the total count is given by cnt/2 as we have count every pair twice in the above traversal.

Below is the implementation of the above approach:

C++
// C++ program to implement // the above approach #include<bits/stdc++.h> using namespace std;  // Function to print the count of pair void countPairs(int N, int arr[]) {     int count = 0;      // Iterate over all the     // elements of the array     for(int i = 0; i < N; i++)     {         if (i == arr[arr[i] - 1] - 1)         {                          // Increment the count             count++;         }     }      // Print the result     cout << (count / 2) << endl; }  // Driver Code int main() {     int arr[] = { 2, 1, 4, 3 };     int N = sizeof(arr)/sizeof(arr[0]);      countPairs(N, arr); }  // This code is contributed by Amit Katiyar 
Java
// Java Program to implement // the above approach import java.util.*;  class GFG {      // Function to print the count of pair     static void countPairs(int N, int[] arr)     {         int count = 0;          // Iterate over all the         // elements of the array         for (int i = 0; i < N; i++) {              if (i == arr[arr[i] - 1] - 1) {                  // Increment the count                 count++;             }         }          // Print the result         System.out.println(count / 2);     }      // Driver Code     public static void main(String[] args)     {         int[] arr = { 2, 1, 4, 3 };         int N = arr.length;          countPairs(N, arr);     } } 
Python3
# Python3 program to implement # the above approach # Function to print the count of pair def countPairs(N, arr):      count = 0      # Iterate over all the     # elements of the array     for i in range(N):         if (i == arr[arr[i] - 1] - 1):                     # Increment the count             count += 1      # Print the result     print(count // 2)  # Driver Code if __name__ == "__main__":        arr = [2, 1, 4, 3]     N = len(arr)     countPairs(N, arr)  # This code is contributed by Chitranayal 
C#
// C# Program to implement // the above approach using System; class GFG{     // Function to print the count of pair   static void countPairs(int N, int[] arr)   {     int count = 0;      // Iterate over all the     // elements of the array     for (int i = 0; i < N; i++)      {       if (i == arr[arr[i] - 1] - 1)        {          // Increment the count         count++;       }     }      // Print the result     Console.Write(count / 2);   }    // Driver Code   public static void Main(string[] args)   {     int[] arr = { 2, 1, 4, 3 };     int N = arr.Length;      countPairs(N, arr);   } }  // This code is contributed by Ritik Bansal 
JavaScript
<script>      // Javascript program to implement     // the above approach          // Function to print the count of pair     function countPairs(N, arr)     {         let count = 0;          // Iterate over all the         // elements of the array         for(let i = 0; i < N; i++)         {             if (i == arr[arr[i] - 1] - 1)             {                  // Increment the count                 count++;             }         }          // Print the result         document.write(count / 2);     }          let arr = [ 2, 1, 4, 3 ];     let N = arr.length;       countPairs(N, arr);      </script> 

Output
2

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


Next Article
Count pairs in an array having sum of elements with their respective sum of digits equal
author
offbeat
Improve
Article Tags :
  • Searching
  • DSA
  • Arrays
Practice Tags :
  • Arrays
  • Searching

Similar Reads

  • Count pairs from an array having GCD equal to the minimum element in the pair
    Given an array arr[] consisting of N integers, the task is to find the number of pairs such that the GCD of any pair of array elements is the minimum element of that pair. Examples: Input: arr[ ] = {2, 3, 1, 2}Output: 4Explanation:Below are the all possible pairs from the given array: (0, 1): The GC
    14 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 pairs in an array having sum of elements with their respective sum of digits equal
    Given an array arr[] consisting of N positive integers, the task is to count the number of pairs in the array, say (a, b) such that sum of a with its sum of digits is equal to sum of b with its sum of digits. Examples: Input: arr[] = {1, 1, 2, 2}Output: 2Explanation:Following are the pairs that sati
    8 min read
  • Count of distinct pairs having one element as K times the other
    Given an array arr[] and an integer K, find the maximum number of pairs that can be made such that one element is K times the other i.e, arr[i]=K*arr[j]. Examples: Input: arr[] = {1, 2, 1, 2, 4} K = 2Output: 2Explanation: There are two possible ways to construct pairs: ({1, 2}, {1, 2}) and ({1, 2},
    5 min read
  • Count equal element pairs in the given array
    Given an array arr[] of N integers representing the lengths of the gloves, the task is to count the maximum possible pairs of gloves from the given array. Note that a glove can only pair with a same-sized glove and it can only be part of a single pair. Examples: Input: arr[] = {6, 5, 2, 3, 5, 2, 2,
    8 min read
  • Number of Good Pairs - Count of index pairs with equal values in an array
    Given an array 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 = [5, 2, 3, 5, 5, 3]Output: 4Explanation: There are 4 good pairs (0, 3), (0, 4), (3, 4), (2, 5) Input: arr = [1, 1, 1, 1]Output: 6Explanation: All 6 pair
    7 min read
  • Count pairs from an array having product of their sum and difference equal to 1
    Given an array arr[] of size N, the task is to count possible pairs of array elements (arr[i], arr[j]) such that (arr[i] + arr[j]) * (arr[i] – arr[j]) is 1. Examples: Input: arr[] = {3, 1, 1, 0} Output: 2 Explanation: The two possible pairs are:  (arr[1] + arr[3]) * (arr[1] – arr[3]) = 1(arr[2] + ar
    5 min read
  • Count pairs from an array having product of their sum and difference equal to 0
    Given an array arr[] of size N, the task is to count possible pairs of array elements (arr[i], arr[j]) such that (arr[i] + arr[j]) * (arr[i] - arr[j]) is 0. Examples: Input: arr[] = {2, -2, 1, 1}Output : 2Explanation:(arr[0] + arr[1]) * (arr[0] - arr[1]) = 0(arr[3] + arr[4]) * (arr[3] - arr[4]) = 0
    8 min read
  • Count of equal value pairs from given two Arrays such that a[i] equals b[j]
    Given two arrays a[] and b[] of length N and M respectively, sorted in non-decreasing order. The task is to find the number of pairs (i, j) such that, a[i] equals b[j]. Examples: Input: a[] = {1, 1, 3, 3, 3, 5, 8, 8}, b[] = {1, 3, 3, 4, 5, 5, 5}Output: 11Explanation: Following are the 11 pairs with
    14 min read
  • Count pairs from two arrays having sum equal to K
    Given an integer K and two arrays A1 and A2, the task is to return the total number of pairs (one element from A1 and one element from A2) with a sum equal to K. Note: Arrays can have duplicate elements. We consider every pair as different, the only constraint is, an element (of any array) can parti
    6 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