Larry’s array

Fermin Blanco
2 min readAug 7, 2023

--

Photo by Nick Fewings on Unsplash

Problem statement

Larry has been given a permutation of a sequence of natural numbers incrementing from 1, as an array. He must determine if the array can be sorted using the following operation any number of times (Choose 3 indexes):

ABCBCACABABC

Inversion

Well there is a concept in discrete mathematics that I cannot fully understand. But I can understand enough to actually use it in the algorithm: Inversion.

An inversion is when a smaller element is to the right of a larger element. For example, in the array [1, 3, 2], the inversions are (1, 3) and (1, 2).

“What’s an interesting property of the inversion number is that the order of the permutation won’t actually affect its even/odd nature for the entire array”

The number of inversion is even

If the number of inversions are even we can fully assert that they array can be sorted.

The number of inversions is odd

Otherwise (the number of inversions are odd), the array cannot be sorted. Having this into account, let’s take advantage of this concept 😊.

The algorithm

So instead of perform every rotation to find out if the array could be sorted, let’s use inversion.

  1. Loop over the array until we found a element in the wrong position
  2. Find the first element that is in correct position
  3. Perform inversions until j > i (Increasing the counter each time)
  4. Finally check if the number of inversions are even or odd

https://g.co/bard/share/120bf6a4dcec

--

--

Fermin Blanco
Fermin Blanco

Written by Fermin Blanco

I write to fill my gaps not to show yours.

No responses yet