We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
- Prepare
- Algorithms
- Implementation
- Larry's Array
- Discussions
Larry's Array
Larry's Array
Sort by
recency
|
361 Discussions
|
Please Login in order to post a comment
this really just asks if you have an even permutation. you can calculate the sign in linear time by multiplying up the signs of each cycle within - the code is relatively straightforward. counting inversions may work too, although this is quadratic
hey,
How come hidden test case 4 1 3 2 would return "YES", obvious it should be "NO" right?
Theory: (a, b, c) -> (b, c, a) is a 3-cycle permutation. That means the permutation (b, c, a) of (a, b, c) is achieved by shifting 3 consecutive numbers(cycle) which are sorted.
Now, if a permutation can be built with even number of swaps, then its even permutation, otherwise it is an odd permutation. Our goal is to built the sorted array from the given one by 3-cycle permutation, which is an even permutation itself.
Now, if (i, j) are two indices such that i) i < j ii) A[i] > A[j] then its called an inversion, which simply means this pair on non-consecutive numbers in an array is unsorted.
It is important to note that every swap of two elements change the parity of inversion count. For example, for an array (4, 3, 1) , 4 > 3 ---> inversion count =1 4 > 1 ----> inversion count =2 3 > 1 ----> inversion count = 3 so, inversion count parity is odd if we swap (3, 1) --> (4, 1, 3) now the inversion count will be 2, which is even parity. Just one swap changes the parity odd to even
Now, a 3-cycle permutation is an even permutation, which preserves the parity of inversion count since the permutation is achived by two swaps in a row. That means if we start with an array which have even number of inversion, after doing the 3-cycle permutation on it any given number of times, the array will still have an even number of inversions or vice versa
Our goal is to make the array 0 inversion count, which is actually an even inversion count. Therefore, if the number of inversion in an array is even, then the array can be sorted by 3-cycle permutation, as the initial parity of inversion count(even) will be preserved and ended with inversion count 0(even as well)
solution in c#:
Here is problem solution in python java c++ c and Javascript - https://programmingoneonone.com/hackerrank-larrys-array-problem-solution.html