Anyone to help me modify my program or write a better solution to this task below



John is a famous shopkeeper who sells n items in her shop. She assigns each item a unique popularity rating in the inclusive range from 1 to n.

The shop only has one shelf, so the items are displayed array-style in a single row spanning from left to right in a random order. He wants to rearrange the items on the shelf by decreasing popularity rating such that the rating for the i item is always greater than the popularity rating of the (i + 1) item. Mary can swap any two items, i and j, in a single operation.



ratings: Array<Number> - an array of numbers indicating the popularity rating of each item on the shelf.

Return Value

Number - denotes the minimum number of swap operations Mary must perform to order all n items by decreasing popularity rating.


n = number of items in ratings array

each rating value ( arri ) will be unique

1 ≤ n ≤ 2 × 105

1 ≤ arri ≤ n

// Here is my solution to the problem above but it does not pass the tests

function minimumSwaps(ratings) {
    var swaps = 0;
    for (var i = 0; i < ratings.length; i++) {
        for (var j = i + 1; j < ratings.length; j++) {
            if (ratings[i] == ratings[j]) {
                ratings[i] = ratings[i] + ratings[j];
            } else {
              swaps = swaps + 1;
   return swaps;

minimumSwaps([4, 3, 1, 2]);


What tests are failing? Is your code returning the correct value? Or is your code returning the correct value but is taking too much time to return it?


It’s only returning the right value for this array here [3,1,2] as 1 swap


And the tests that are;

Should Handle Multiple Swaps

expected 1 to equal 2

** Should Handle Multiple Swaps On Large Arrays**

expected 1 to equal 39

**** Should Handle Zero Swap****

expected 1 to equal 0


I have tried to modify the code and now looks like this but still failing to pass the tests

the code looks like this now
function minimumSwaps (ratings) {
var swaps = 0;
var n = 1;
for (var i = 1; i < i.length; i++) {
if (ratings[i] == ratings[j]) {
n = n + 1;
} else {
swaps = swaps + 1;
return n;

console.log(minimumSwaps([3, 1, 2]));


Hi Kirupa;
Any suggestion to my code?


I will try to take a look at it tomorrow, for my brain is fried tonight from a bunch of other programming things :stuck_out_tongue_winking_eye:


Oh no !


Though any suggestion to my code is welcome.