Larry's Array

Larry's Array - A HackerRank challenge solution

Problem

Larry has been given a permutation of a sequence of natural numbers incrementing from 1 as an array. He must determine whether the array can be sorted using the following operation any number of times:

  • Choose any consecutive indices and rotate their elements in such a way that ABC -> BCA -> CAB -> ABC.

For example, if :

A		rotate 
[1,6,5,2,4,3]	[6,5,2]
[1,5,2,6,4,3]	[5,2,6]
[1,2,6,5,4,3]	[5,4,3]
[1,2,6,3,5,4]	[6,3,5]
[1,2,3,5,6,4]	[5,6,4]
[1,2,3,4,5,6]

YES

On a new line for each test case, print YES if A can be fully sorted. Otherwise, print NO.

Read more on the challenge page…

My Solution

I’m providing the solution for Python and JS, please leave on the comments if you found a better way.

That I could think of, there are 2 approaches to solve this problem. The first one being the obvious, doing all the permutations and evaluating at the end when 2 items are left if they are in order.

The other way, which happens I knew it already, has to do with inversion . Inversions are particularly interesting for this problem. Now if you don’t know about inversions, is very unlikely to find this solution on your own.

By definition, The inversion number is the cardinality of inversion set. It is a common measure of the sortedness of a permutation or sequence.

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.

Here is that demonstrated with a few examples:

Example 1: 312

inversion(312) = 2

312 -> 123 = sorted!

Example 2: 231

inversion(231) = 2

231 -> 312 -> 123 = sorted!

Example 3: 213

inversion(231) = 1

213 -> 132 -> 321 -> 213 != can't be sorted 

So we can say that only those combinations with even inversion number can be sorted, and that’s what we are going for.

If you liked what you saw, please support my work!

Juan Cruz Martinez - Author @ Live Code Stream

Juan Cruz Martinez

Juan has made it his mission to help aspiring developers unlock their full potential. With over two decades of hands-on programming experience, he understands the challenges and rewards of learning to code. By providing accessible and engaging educational content, Juan has cultivated a community of learners who share their passion for coding. Leveraging his expertise and empathetic teaching approach, Juan has successfully guided countless students on their journey to becoming skilled developers, transforming lives through the power of technology.