From Quadratic to Linear: a Medium LeetCode Problem

Problem statement: https://leetcode.com/problems/global-and-local-inversions/description/

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 1:
Input: A = [1,0,2]
Output: true
Explanation: There is 1 global inversion, and 1 local inversion.
Example 2:
Input: A = [1,2,0]
Output: false
Explanation: There are 2 global inversions, and 1 local inversion.
If you were like me the first solution that comes to mind is a straightforward count:

  • Count local inversions
  • Now, count global inversions
  • Compare
Only one problem, though: it is N^2, and since the N=5000, this is 25,000,000 iterations, and the LeetCode gods don't like it:



There are two options now, either go with NLogN (some sort of variation of QuickSort or MergeSort), or we need to think about a Dynamic Programming (DP) like solution. Let's think about the problem....

A local inversion is by definition a global inversion. But not all global inversions are local inversions.

Therefore, all we need to do is to find a global inversion that is not a local inversion. If we find one, then for sure we'll have more global inversions than local inversions. If we don't find, they are the same.

A global inversion that is not a local inversion is one where A[i] > A[j] for some (any) i < j - 1. In other words, find a number in the array that is greater than another number to its right that is not adjacent to itself.

To do so here is the approach: keep track of the MAX number seen so far to the left of index "i". Then check whether MAX is greater than A[i+1]. If so, you found a global inversion that is NOT a local inversion and as such you should return false.

See it does not matter where MAX is, as long as it is located to the left of "i" (not including "i" itself).

Then as you move "i" you discard the previous MAX and have a new MAX.

One pass - linear solution.

To explain this logic in English took way longer than writing the code... Cheers, Marcelo.

public bool IsIdealPermutation(int[] A)
{
int maxBeforeCurrent = Int32.MinValue;
for (int i = 0; i < A.Length; i++)
{
if (i + 1 < A.Length && maxBeforeCurrent > A[i + 1]) return false;
maxBeforeCurrent = A[i] > maxBeforeCurrent ? A[i] : maxBeforeCurrent;
}
return true;
}

Comments

  1. Rust one-liner :)

    impl Solution {
    pub fn is_ideal_permutation(a: Vec) -> bool {
    a.iter().enumerate().all(|(idx, val)| (idx as i32 - val).abs() <= 1)
    }
    }

    Reply Delete

Post a Comment

[フレーム]

Popular posts from this blog

Quasi FSM (Finite State Machine) problem + Vibe

Not really an FSM problem since the state isn't changing, it is just defined by the current input. Simply following the instructions should do it. Using VSCode IDE you can also engage the help of Cline or Copilot for a combo of coding and vibe coding, see below screenshot. Cheers, ACC. Process String with Special Operations I - LeetCode You are given a string  s  consisting of lowercase English letters and the special characters:  * ,  # , and  % . Build a new string  result  by processing  s  according to the following rules from left to right: If the letter is a  lowercase  English letter append it to  result . A  '*'   removes  the last character from  result , if it exists. A  '#'   duplicates  the current  result  and  appends  it to itself. A  '%'   reverses  the current  result . Return the final string  result  after processing all char...

Shortest Bridge – A BFS Story (with a Twist)

Here's another one from the Google 30 Days challenge on LeetCode — 934. Shortest Bridge . The goal? Given a 2D binary grid where two islands (groups of 1s) are separated by water (0s), flip the fewest number of 0s to 1s to connect them. Easy to describe. Sneaky to implement well. 🧭 My Approach My solution follows a two-phase Breadth-First Search (BFS) strategy: Find and mark one island : I start by scanning the grid until I find the first 1 , then use BFS to mark all connected land cells as 2 . I store their positions for later use. Bridge-building BFS : For each cell in the marked island, I run a BFS looking for the second island. Each BFS stops as soon as it hits a cell with value 1 . The minimum distance across all these searches gives the shortest bridge. πŸ” Code Snippet Here's the core logic simplified: public int ShortestBridge(int[][] grid) { // 1. Mark one island as '2' and gather its coordinates List<int> island = FindAndMark...

Classic Dynamic Programming IX

A bit of vibe code together with OpenAI O3. I asked O3 to just generate the sieve due to laziness. Sieve is used to calculate the first M primes (when I was using Miller-Rabin, was giving me TLE). The DP follows from that in a straightforward way: calculate the numbers from i..n-1, then n follows by calculating the min over all M primes. Notice that I made use of Goldbach's Conjecture as a way to optimize the code too. Goldbach's Conjecture estates that any even number greater than 2 is the sum of 2 primes. The conjecture is applied in the highlighted line. Cheers, ACC. PS: the prompt for the sieve was the following, again using Open AI O3 Advanced Reasoning: " give me a sieve to find the first M prime numbers in C#. The code should produce a List<int> with the first M primes " Minimum Number of Primes to Sum to Target - LeetCode You are given two integers  n  and  m . You have to select a multiset of  prime numbers  from the  first   m  pri...