Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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 are indices i < j such that nums[i] > nums[j]. And a local inversion is when there is an index i 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.
Key Insight
Every local inversion is also a global inversion. So if the counts are equal, there should be no "extra" global inversions beyond the local ones. This means we only need to check if there's any element at position i that is greater than any element at position j where j > i + 1.
Algorithm
To solve this, we will follow these steps −
- Get the length of nums
- For each index i from 0 to length - 3, do
- For each index j from i + 2 to length - 1, do
- If nums[i] > nums[j], then return False
- For each index j from i + 2 to length - 1, do
- Return True
Example
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
# Test the solution
ob = Solution()
nums = [3, 2, 4]
print(ob.solve(nums))
True
How It Works
Let's trace through the example [3, 2, 4] ?
nums = [3, 2, 4]
# Check all pairs where j > i + 1
# i=0, j=2: nums[0]=3, nums[2]=4 ? 3 < 4 ?
# No violations found, so return True
print("Global inversions:", [(i, j) for i in range(len(nums)) for j in range(i+1, len(nums)) if nums[i] > nums[j]])
print("Local inversions:", [(i, i+1) for i in range(len(nums)-1) if nums[i] > nums[i+1]])
Global inversions: [(0, 1)] Local inversions: [(0, 1)]
Additional Examples
ob = Solution()
# Example 1: Equal counts
test1 = [1, 0, 2]
print(f"nums = {test1}: {ob.solve(test1)}")
# Example 2: Different counts
test2 = [1, 2, 0]
print(f"nums = {test2}: {ob.solve(test2)}")
nums = [1, 0, 2]: True nums = [1, 2, 0]: False
Conclusion
The solution efficiently checks if global and local inversion counts are equal by identifying any "extra" global inversions. If no element at position i is greater than any element at position j > i + 1, then the counts are equal.
