Similar Problems

Similar Problems not available

Global And Local Inversions - Leetcode Solution

Companies:

LeetCode:  Global And Local Inversions Leetcode Solution

Difficulty: Medium

Topics: math array  

Problem Statement:

We have some permutation A of [0, 1, ..., N - 1], where N is the length of A.

The number of (global) inversions is the number of i < j with 0 <= i < j < N and A[i] > A[j].

The number of local inversions is the number of i with 0 <= i < N and A[i] > A[i+1].

Return true if and only if the number of global inversions is equal to the number of local inversions.

Example:

Input: A = [1,0,2] Output: true Explanation: There is 1 global inversion, and 1 local inversion.

Input: A = [1,2,0] Output: false Explanation: There are 2 global inversions, and 1 local inversion.

Solution:

The given problem can be solved using a single pass through the array A. We can keep track of the maximum value we have seen so far and check if the current value is larger than that. If it is, we have a local inversion.

We can also keep track of the minimum and maximum values we have seen so far and check if the current value is smaller than the minimum or larger than the maximum. If it is, we have a global inversion.

To understand the logic behind this solution, let's take an example:

Consider the input A = [1,0,2]. Initially, the minimum and maximum values are set to be A[0], which is 1. We also initialize the variable numGlobalInversions = numLocalInversions = 0.

We start iterating through the array A, starting from the second element. At each step, we check if the current element is larger than the maximum value we have seen so far (which is currently 1). Since 0 < 1, this condition is not satisfied and we move on.

Next, we check if the current element is smaller than the minimum value we have seen so far (which is currently 1). Since 0 < 1, this condition is satisfied and we increment the variable numGlobalInversions.

We then update the minimum value to be the minimum of the current element and the previous minimum. In this case, the minimum remains unchanged.

We repeat the same steps for the last element, which is 2. We first check if it is larger than the maximum value we have seen so far (which is 1). Since 2 > 1, we have a local inversion. We update the maximum value to be the maximum of the current element and the previous maximum, which is 2.

We then check if 2 is smaller than the minimum value we have seen so far (which is 0). Since 2 > 0, this condition is not satisfied.

Finally, we return true since the number of local inversions is equal to the number of global inversions, which is 1.

The time complexity of this algorithm is O(n), where n is the length of the input array A. The space complexity is O(1), since we only need to store a few variables to keep track of the minimum, maximum, and number of inversions.

Global And Local Inversions Solution Code

1