Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • 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
  • PHP Tutorial
  • PHP Exercises
  • PHP Array
  • PHP String
  • PHP Calendar
  • PHP Filesystem
  • PHP Math
  • PHP Programs
  • PHP Array Programs
  • PHP String Programs
  • PHP Interview Questions
  • PHP GMP
  • PHP IntlChar
  • PHP Image Processing
  • PHP DsSet
  • PHP DsMap
  • PHP Formatter
  • Web Technology
Open In App
Next Article:
PHP Program to Count Inversions of size three in a given array
Next article icon

PHP Program to Count Inversions of size three in a given array

Last Updated : 23 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array arr[] of size n. Three elements arr[i], arr[j] and arr[k] form an inversion of size 3 if a[i] > a[j] >a[k] and i < j < k. Find total number of inversions of size 3.

Example : 

Input:  {8, 4, 2, 1}
Output: 4
The four inversions are (8,4,2), (8,4,1), (4,2,1) and (8,2,1).

Input: {9, 6, 4, 5, 8}
Output: 2
The two inversions are {9, 6, 4} and {9, 6, 5}

Simple approach

Loop for all possible value of i, j and k and check for the condition a[i] > a[j] > a[k] and i < j < k.

PHP
<?php // A O(n^2) PHP program to  // count inversions of size 3  // Returns count of  // inversions of size 3 function getInvCount($arr, $n) {          // Initialize result     $invcount = 0;       for ($i = 1; $i < $n - 1; $i++)     {                  // Count all smaller elements          // on right of arr[i]         $small = 0;         for($j = $i + 1; $j < $n; $j++)             if ($arr[$i] > $arr[$j])                 $small++;          // Count all greater elements          // on left of arr[i]         $great = 0;         for($j = $i - 1; $j >= 0; $j--)             if ($arr[$i] < $arr[$j])                 $great++;          // Update inversion count by          // adding all inversions         // that have arr[i] as          // middle of three elements         $invcount += $great * $small;     }      return $invcount; }      // Driver Code     $arr = array(8, 4, 2, 1);     $n = sizeof($arr);     echo "Inversion Count : "         , getInvCount($arr, $n);  // This code is contributed m_kit ?> 

Output
Inversion Count : 4

Complexity Analysis: 

  • Time complexity of this approach is : O(n^3)
  • Auxiliary Space: O(1)

As constant extra space is used.

Better Approach

We can reduce the complexity if we consider every element arr[i] as middle element of inversion, find all the numbers greater than a[i] whose index is less than i, find all the numbers which are smaller than a[i] and index is more than i. We multiply the number of elements greater than a[i] to the number of elements smaller than a[i] and add it to the result. 

Below is the implementation of the idea.

PHP
<?php // A O(n^2) PHP program to count // inversions of size 3  // Returns count of  // inversions of size 3 function getInvCount($arr, $n) {     // Initialize result     $invcount = 0;       for ($i = 1; $i < $n - 1; $i++)     {         // Count all smaller elements         // on right of arr[i]         $small = 0;         for ($j = $i + 1; $j < $n; $j++)             if ($arr[$i] > $arr[$j])                 $small++;          // Count all greater elements         // on left of arr[i]         $great = 0;         for ($j = $i - 1; $j >= 0; $j--)             if ($arr[$i] < $arr[$j])                 $great++;          // Update inversion count by          // adding all inversions that         // have arr[i] as middle of          // three elements         $invcount += $great * $small;     }      return $invcount; }  // Driver Code $arr = array (8, 4, 2, 1); $n = sizeof($arr); echo "Inversion Count : " ,        getInvCount($arr, $n);      // This code is contributed by m_kit ?> 

Output
Inversion Count : 4

Complexity Analysis: 

  • Time Complexity of this approach : O(n^2)
  • Auxiliary Space: O(1)

As constant extra space is used.

Binary Indexed Tree Approach : 

Like inversions of size 2, we can use Binary indexed tree to find inversions of size 3. It is strongly recommended to refer below article first.

count inversions of size two Using BIT

The idea is similar to above method. We count the number of greater elements and smaller elements for all the elements and then multiply greater[] to smaller[] and add it to the result. 

Solution :

  1. To find out the number of smaller elements for an index we iterate from n-1 to 0. For every element a[i] we calculate the getSum() function for (a[i]-1) which gives the number of elements till a[i]-1.
  2. To find out the number of greater elements for an index we iterate from 0 to n-1. For every element a[i] we calculate the sum of numbers till a[i] (sum smaller or equal to a[i]) by getSum() and subtract it from i (as i is the total number of element till that point) so that we can get number of elements greater than a[i].

Please refer complete article on Count Inversions of size three in a given array for more details!


Next Article
PHP Program to Count Inversions of size three in a given array

K

kartik
Improve
Article Tags :
  • PHP
  • Binary Indexed Tree
  • inversion

Similar Reads

    Javascript Program to Count Inversions of size three in a given array
    Given an array arr[] of size n. Three elements arr[i], arr[j] and arr[k] form an inversion of size 3 if a[i] > a[j] >a[k] and i < j < k. Find total number of inversions of size 3.Example : Input: {8, 4, 2, 1}Output: 4The four inversions are (8,4,2), (8,4,1), (4,2,1) and (8,2,1).Input: {9
    4 min read
    Count Inversions of size three in a given array
    Given an array arr[] of size n. Three elements arr[i], arr[j] and arr[k] form an inversion of size 3 if a[i] > a[j] >a[k] and i < j < k. Find total number of inversions of size 3. Example : Input: {8, 4, 2, 1} Output: 4 The four inversions are (8,4,2), (8,4,1), (4,2,1) and (8,2,1). Input
    15+ min read
    Count inversions of size k in a given array
    Given an array of n distinct integers a_{1}, a_{2}, ..., a_{n} and an integer k. Find out the number of sub-sequences of a such that a_{i_{1}} > a_{i_{2}} > ... > a_{i_{k}} , and 1 <= i_{1} < i_{2} < ... < i_{k} <= n . In other words output the total number of inversions of l
    14 min read
    Counting segment inversions of an Array with updates
    Given an array of small integers arr[] and a 2D array of queries[][], In each query array we have the first element indicating the operation type, and the remaining elements are the arguments. If query[i][0] is '1' then query[i][1] = l and query[i][2] = r and we have to Find the number of inversions
    15+ min read
    Counting inversions in all subarrays of given size
    Given an array and an integer k, count all inversions in all subarrays of size k. Example: Input : a[] = {7, 3, 2, 4, 1}, k = 3; Output : 6 Explanation: subarrays of size 3 are - {7, 3, 2} {3, 2, 4} {2, 4, 1} and there inversion count are 3, 1, 2 respectively. So, total number of inversions are 6. I
    15+ 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