Program to check number of global and local inversions are same or not in Python

Suppose we have a list of distinct numbers called nums. Here a global inversion is when there's indices i < j such that nums[i] > nums[j]. And local inversion is when there is an index i and i + 1 such that nums[i] > nums[i + 1]. We have to check whether the number of global inversions is equal to the number of local inversions or not.

So, if the input is like nums = [3, 2, 4], then the output will be True, as the indices 0 and 1 are both a global and local inversion.

To solve this, we will follow these steps −

  • l := size of nums
  • for i in range 0 to l - 3, do
    • for j in range i + 2 to l-1, do
      • if nums[i] > nums[j], then
        • return False
  • return True

Let us see the following implementation to get better understanding −


 Live Demo

class Solution:
   def solve(self, nums):
      l = len(nums)
      for i in range(l - 2):
         for j in range(i + 2, l):
            if nums[i] > nums[j]:
               return False
      return True
ob = Solution()
nums = [3, 2, 4]


[3, 2, 4]



Updated on: 19-Nov-2020


Kickstart Your Career

Get certified by completing the course

Get Started