Minimum swaps algorithm terminated due to timeoutSPOJ GENERAL: sorting by swaps of distance kHackerrank Insertion Sort Algorithm 1 (creating duplicates to show shifting)Terminated due to timeout Mapping phone numbersDetermining the cardinality of sets defined by recursively following indexesSearching the Array Index & Element EqualityK Messed Array sort in JavaClimbing the Leaderboard: HackerranK, Terminated due to timeoutMinimum number of swaps required to sort the array in ascending orderTwo-sum solution in JavaScriptFind array index with element equality in Python

Do I have a twin with permutated remainders?

How can I prevent hyper evolved versions of regular creatures from wiping out their cousins?

Mage Armor with Defense fighting style (for Adventurers League bladeslinger)

Arthur Somervell: 1000 Exercises - Meaning of this notation

Why are electrically insulating heatsinks so rare? Is it just cost?

TGV timetables / schedules?

Can an x86 CPU running in real mode be considered to be basically an 8086 CPU?

US citizen flying to France today and my passport expires in less than 2 months

In Japanese, what’s the difference between “Tonari ni” (となりに) and “Tsugi” (つぎ)? When would you use one over the other?

Either or Neither in sentence with another negative

Languages that we cannot (dis)prove to be Context-Free

Why doesn't H₄O²⁺ exist?

Does Unearthed Arcana render Favored Souls redundant?

What typically incentivizes a professor to change jobs to a lower ranking university?

Is it tax fraud for an individual to declare non-taxable revenue as taxable income? (US tax laws)

Can I ask the recruiters in my resume to put the reason why I am rejected?

Writing rule stating superpower from different root cause is bad writing

Font hinting is lost in Chrome-like browsers (for some languages )

How did the USSR manage to innovate in an environment characterized by government censorship and high bureaucracy?

Did Shadowfax go to Valinor?

Finding angle with pure Geometry.

Approximately how much travel time was saved by the opening of the Suez Canal in 1869?

Why not use SQL instead of GraphQL?

Why is consensus so controversial in Britain?



Minimum swaps algorithm terminated due to timeout


SPOJ GENERAL: sorting by swaps of distance kHackerrank Insertion Sort Algorithm 1 (creating duplicates to show shifting)Terminated due to timeout Mapping phone numbersDetermining the cardinality of sets defined by recursively following indexesSearching the Array Index & Element EqualityK Messed Array sort in JavaClimbing the Leaderboard: HackerranK, Terminated due to timeoutMinimum number of swaps required to sort the array in ascending orderTwo-sum solution in JavaScriptFind array index with element equality in Python






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








4












$begingroup$


I have been trying to solve this question.




Given an unordered array consisting of consecutive integers [1, 2, 3, …, n], find the minimum number of two-element swaps to sort the array.




I was able to solve it but my solution's complexity is not good enough that it terminated due to a timeout when it runs with bigger arrays. This is a typical problem for me, I always solve the problem somehow but the complexity is not optimal and the solution does not pass the all the cast cases. If you have any suggestions for me for the future interview questions like that, I'd appreciate knowing how should I approach the questions.



function findIndice(arr,i)
let iterator=0
while(arr[iterator]!==i+1)
iterator++

return iterator


function swap(arr,x,y)
let temp=arr[x]
arr[x]=arr[y]
arr[y]=temp




function minimumSwaps(arr)
let i=0;
let counter=0;
let size=arr.length;

for(i=0;i<size-1;i++)
if(arr[i]!==i+1)
let index=findIndice(arr,i)
swap(arr,index,i)
counter++


return counter










share|improve this question











$endgroup$











  • $begingroup$
    This is a totally different question... @Gerrit0
    $endgroup$
    – Ugur Yilmaz
    Aug 12 '18 at 2:26










  • $begingroup$
    Oh shoot, you are totally right. I must have sent the wrong link as I looked at several... sorry about that!
    $endgroup$
    – Gerrit0
    Aug 12 '18 at 2:48










  • $begingroup$
    That's okay, Thanks for trying to help :) @Gerrit0
    $endgroup$
    – Ugur Yilmaz
    Aug 12 '18 at 3:50

















4












$begingroup$


I have been trying to solve this question.




Given an unordered array consisting of consecutive integers [1, 2, 3, …, n], find the minimum number of two-element swaps to sort the array.




I was able to solve it but my solution's complexity is not good enough that it terminated due to a timeout when it runs with bigger arrays. This is a typical problem for me, I always solve the problem somehow but the complexity is not optimal and the solution does not pass the all the cast cases. If you have any suggestions for me for the future interview questions like that, I'd appreciate knowing how should I approach the questions.



function findIndice(arr,i)
let iterator=0
while(arr[iterator]!==i+1)
iterator++

return iterator


function swap(arr,x,y)
let temp=arr[x]
arr[x]=arr[y]
arr[y]=temp




function minimumSwaps(arr)
let i=0;
let counter=0;
let size=arr.length;

for(i=0;i<size-1;i++)
if(arr[i]!==i+1)
let index=findIndice(arr,i)
swap(arr,index,i)
counter++


return counter










share|improve this question











$endgroup$











  • $begingroup$
    This is a totally different question... @Gerrit0
    $endgroup$
    – Ugur Yilmaz
    Aug 12 '18 at 2:26










  • $begingroup$
    Oh shoot, you are totally right. I must have sent the wrong link as I looked at several... sorry about that!
    $endgroup$
    – Gerrit0
    Aug 12 '18 at 2:48










  • $begingroup$
    That's okay, Thanks for trying to help :) @Gerrit0
    $endgroup$
    – Ugur Yilmaz
    Aug 12 '18 at 3:50













4












4








4





$begingroup$


I have been trying to solve this question.




Given an unordered array consisting of consecutive integers [1, 2, 3, …, n], find the minimum number of two-element swaps to sort the array.




I was able to solve it but my solution's complexity is not good enough that it terminated due to a timeout when it runs with bigger arrays. This is a typical problem for me, I always solve the problem somehow but the complexity is not optimal and the solution does not pass the all the cast cases. If you have any suggestions for me for the future interview questions like that, I'd appreciate knowing how should I approach the questions.



function findIndice(arr,i)
let iterator=0
while(arr[iterator]!==i+1)
iterator++

return iterator


function swap(arr,x,y)
let temp=arr[x]
arr[x]=arr[y]
arr[y]=temp




function minimumSwaps(arr)
let i=0;
let counter=0;
let size=arr.length;

for(i=0;i<size-1;i++)
if(arr[i]!==i+1)
let index=findIndice(arr,i)
swap(arr,index,i)
counter++


return counter










share|improve this question











$endgroup$




I have been trying to solve this question.




Given an unordered array consisting of consecutive integers [1, 2, 3, …, n], find the minimum number of two-element swaps to sort the array.




I was able to solve it but my solution's complexity is not good enough that it terminated due to a timeout when it runs with bigger arrays. This is a typical problem for me, I always solve the problem somehow but the complexity is not optimal and the solution does not pass the all the cast cases. If you have any suggestions for me for the future interview questions like that, I'd appreciate knowing how should I approach the questions.



function findIndice(arr,i)
let iterator=0
while(arr[iterator]!==i+1)
iterator++

return iterator


function swap(arr,x,y)
let temp=arr[x]
arr[x]=arr[y]
arr[y]=temp




function minimumSwaps(arr)
let i=0;
let counter=0;
let size=arr.length;

for(i=0;i<size-1;i++)
if(arr[i]!==i+1)
let index=findIndice(arr,i)
swap(arr,index,i)
counter++


return counter







javascript algorithm sorting time-limit-exceeded interview-questions






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Aug 11 '18 at 22:12









200_success

131k17157422




131k17157422










asked Aug 11 '18 at 17:11









Ugur YilmazUgur Yilmaz

413




413











  • $begingroup$
    This is a totally different question... @Gerrit0
    $endgroup$
    – Ugur Yilmaz
    Aug 12 '18 at 2:26










  • $begingroup$
    Oh shoot, you are totally right. I must have sent the wrong link as I looked at several... sorry about that!
    $endgroup$
    – Gerrit0
    Aug 12 '18 at 2:48










  • $begingroup$
    That's okay, Thanks for trying to help :) @Gerrit0
    $endgroup$
    – Ugur Yilmaz
    Aug 12 '18 at 3:50
















  • $begingroup$
    This is a totally different question... @Gerrit0
    $endgroup$
    – Ugur Yilmaz
    Aug 12 '18 at 2:26










  • $begingroup$
    Oh shoot, you are totally right. I must have sent the wrong link as I looked at several... sorry about that!
    $endgroup$
    – Gerrit0
    Aug 12 '18 at 2:48










  • $begingroup$
    That's okay, Thanks for trying to help :) @Gerrit0
    $endgroup$
    – Ugur Yilmaz
    Aug 12 '18 at 3:50















$begingroup$
This is a totally different question... @Gerrit0
$endgroup$
– Ugur Yilmaz
Aug 12 '18 at 2:26




$begingroup$
This is a totally different question... @Gerrit0
$endgroup$
– Ugur Yilmaz
Aug 12 '18 at 2:26












$begingroup$
Oh shoot, you are totally right. I must have sent the wrong link as I looked at several... sorry about that!
$endgroup$
– Gerrit0
Aug 12 '18 at 2:48




$begingroup$
Oh shoot, you are totally right. I must have sent the wrong link as I looked at several... sorry about that!
$endgroup$
– Gerrit0
Aug 12 '18 at 2:48












$begingroup$
That's okay, Thanks for trying to help :) @Gerrit0
$endgroup$
– Ugur Yilmaz
Aug 12 '18 at 3:50




$begingroup$
That's okay, Thanks for trying to help :) @Gerrit0
$endgroup$
– Ugur Yilmaz
Aug 12 '18 at 3:50










2 Answers
2






active

oldest

votes


















3












$begingroup$

Your algorithm can be summarized by the pseudocode:



for each position in the array
if a position is occupied by the wrong number
find the number that fits into the position
perform a swap


A better algorithm would be:



for each position in the array
if a number is in the wrong location
find the position the number should go
perform a swap


This is because finding a number for a given location requires a linear scan, but finding the location for a given number is as simple as it gets: the number five should go into the fifth position.



The full program could look like this (in python, as I don't speak js):



def minimumSwaps(arr):
def swap(i, j):
arr[i], arr[j] = arr[j], arr[i]
swaps = 0
for i in range(0, len(arr)):
while arr[i]-1 != i:
swap(i, arr[i]-1)
swaps += 1
return swaps





share|improve this answer









$endgroup$












  • $begingroup$
    This is a great solution but it fails if the numbers are not consecutive. To illustrate; 1 3 5 2 4 6 8 does not pass this test case @Rainer P.
    $endgroup$
    – Ugur Yilmaz
    Aug 12 '18 at 17:25







  • 1




    $begingroup$
    @UgurYilmaz - Your question literaly says [...] consisting of consecutive integers [...].
    $endgroup$
    – Rainer P.
    Aug 12 '18 at 18:55











  • $begingroup$
    I know but there should be an error in hackerRank, then. Because there is a test case with that input and it seems to fail. Do you have any idea how to implement a solution efficiently if it is not a consecutive array integers @Rainer P.
    $endgroup$
    – Ugur Yilmaz
    Aug 12 '18 at 19:50











  • $begingroup$
    There aren't such cases, I tried the solution above and it was accepted.
    $endgroup$
    – user158037
    Oct 12 '18 at 16:07


















0












$begingroup$

The fastest way so far I tried is



  1. For each iteration of "i"

  2. Try to find out from the list ( i - 1, arr.length ) if there is an item misplaced

  3. If there is an misplaced item, swap it




const minimalSwap = (arr) => 
// don't mutate the original array
let list = [...arr]
// length of the list
const listLen = list.length
// state - total swap
let totalSwap = 0
if (listLen <= 1)
return totalSwap

function swap(items, idxOne, idxTwo)
let tempNode = items[idxOne]
items[idxOne] = items[idxTwo]
items[idxTwo] = tempNode
totalSwap += 1
return items

for (let i = 0; i < listLen; i++)
// for each iteration, we find the
// number that should go to the correct position
let idToSwap = false
const correctNumber = i + 1
// iterate through starting next item
// and find if the correct number is misplaced
for (let j = i + 1; j < listLen; j++)
// if it is misplaced, swap it
if (correctNumber === list[j])
idToSwap = j
break;


if (idToSwap)
list = swap(list, i, idToSwap)



return totalSwap


// test case
minimalSwap([14, 15, 16, 4, 8, 3, 1, 2, 5, 7, 9, 10, 11, 12, 13, 6])







share








New contributor




R.R is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.






$endgroup$













    Your Answer





    StackExchange.ifUsing("editor", function ()
    return StackExchange.using("mathjaxEditing", function ()
    StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix)
    StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
    );
    );
    , "mathjax-editing");

    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "196"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: false,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: null,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f201470%2fminimum-swaps-algorithm-terminated-due-to-timeout%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    3












    $begingroup$

    Your algorithm can be summarized by the pseudocode:



    for each position in the array
    if a position is occupied by the wrong number
    find the number that fits into the position
    perform a swap


    A better algorithm would be:



    for each position in the array
    if a number is in the wrong location
    find the position the number should go
    perform a swap


    This is because finding a number for a given location requires a linear scan, but finding the location for a given number is as simple as it gets: the number five should go into the fifth position.



    The full program could look like this (in python, as I don't speak js):



    def minimumSwaps(arr):
    def swap(i, j):
    arr[i], arr[j] = arr[j], arr[i]
    swaps = 0
    for i in range(0, len(arr)):
    while arr[i]-1 != i:
    swap(i, arr[i]-1)
    swaps += 1
    return swaps





    share|improve this answer









    $endgroup$












    • $begingroup$
      This is a great solution but it fails if the numbers are not consecutive. To illustrate; 1 3 5 2 4 6 8 does not pass this test case @Rainer P.
      $endgroup$
      – Ugur Yilmaz
      Aug 12 '18 at 17:25







    • 1




      $begingroup$
      @UgurYilmaz - Your question literaly says [...] consisting of consecutive integers [...].
      $endgroup$
      – Rainer P.
      Aug 12 '18 at 18:55











    • $begingroup$
      I know but there should be an error in hackerRank, then. Because there is a test case with that input and it seems to fail. Do you have any idea how to implement a solution efficiently if it is not a consecutive array integers @Rainer P.
      $endgroup$
      – Ugur Yilmaz
      Aug 12 '18 at 19:50











    • $begingroup$
      There aren't such cases, I tried the solution above and it was accepted.
      $endgroup$
      – user158037
      Oct 12 '18 at 16:07















    3












    $begingroup$

    Your algorithm can be summarized by the pseudocode:



    for each position in the array
    if a position is occupied by the wrong number
    find the number that fits into the position
    perform a swap


    A better algorithm would be:



    for each position in the array
    if a number is in the wrong location
    find the position the number should go
    perform a swap


    This is because finding a number for a given location requires a linear scan, but finding the location for a given number is as simple as it gets: the number five should go into the fifth position.



    The full program could look like this (in python, as I don't speak js):



    def minimumSwaps(arr):
    def swap(i, j):
    arr[i], arr[j] = arr[j], arr[i]
    swaps = 0
    for i in range(0, len(arr)):
    while arr[i]-1 != i:
    swap(i, arr[i]-1)
    swaps += 1
    return swaps





    share|improve this answer









    $endgroup$












    • $begingroup$
      This is a great solution but it fails if the numbers are not consecutive. To illustrate; 1 3 5 2 4 6 8 does not pass this test case @Rainer P.
      $endgroup$
      – Ugur Yilmaz
      Aug 12 '18 at 17:25







    • 1




      $begingroup$
      @UgurYilmaz - Your question literaly says [...] consisting of consecutive integers [...].
      $endgroup$
      – Rainer P.
      Aug 12 '18 at 18:55











    • $begingroup$
      I know but there should be an error in hackerRank, then. Because there is a test case with that input and it seems to fail. Do you have any idea how to implement a solution efficiently if it is not a consecutive array integers @Rainer P.
      $endgroup$
      – Ugur Yilmaz
      Aug 12 '18 at 19:50











    • $begingroup$
      There aren't such cases, I tried the solution above and it was accepted.
      $endgroup$
      – user158037
      Oct 12 '18 at 16:07













    3












    3








    3





    $begingroup$

    Your algorithm can be summarized by the pseudocode:



    for each position in the array
    if a position is occupied by the wrong number
    find the number that fits into the position
    perform a swap


    A better algorithm would be:



    for each position in the array
    if a number is in the wrong location
    find the position the number should go
    perform a swap


    This is because finding a number for a given location requires a linear scan, but finding the location for a given number is as simple as it gets: the number five should go into the fifth position.



    The full program could look like this (in python, as I don't speak js):



    def minimumSwaps(arr):
    def swap(i, j):
    arr[i], arr[j] = arr[j], arr[i]
    swaps = 0
    for i in range(0, len(arr)):
    while arr[i]-1 != i:
    swap(i, arr[i]-1)
    swaps += 1
    return swaps





    share|improve this answer









    $endgroup$



    Your algorithm can be summarized by the pseudocode:



    for each position in the array
    if a position is occupied by the wrong number
    find the number that fits into the position
    perform a swap


    A better algorithm would be:



    for each position in the array
    if a number is in the wrong location
    find the position the number should go
    perform a swap


    This is because finding a number for a given location requires a linear scan, but finding the location for a given number is as simple as it gets: the number five should go into the fifth position.



    The full program could look like this (in python, as I don't speak js):



    def minimumSwaps(arr):
    def swap(i, j):
    arr[i], arr[j] = arr[j], arr[i]
    swaps = 0
    for i in range(0, len(arr)):
    while arr[i]-1 != i:
    swap(i, arr[i]-1)
    swaps += 1
    return swaps






    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Aug 12 '18 at 10:25









    Rainer P.Rainer P.

    1,261414




    1,261414











    • $begingroup$
      This is a great solution but it fails if the numbers are not consecutive. To illustrate; 1 3 5 2 4 6 8 does not pass this test case @Rainer P.
      $endgroup$
      – Ugur Yilmaz
      Aug 12 '18 at 17:25







    • 1




      $begingroup$
      @UgurYilmaz - Your question literaly says [...] consisting of consecutive integers [...].
      $endgroup$
      – Rainer P.
      Aug 12 '18 at 18:55











    • $begingroup$
      I know but there should be an error in hackerRank, then. Because there is a test case with that input and it seems to fail. Do you have any idea how to implement a solution efficiently if it is not a consecutive array integers @Rainer P.
      $endgroup$
      – Ugur Yilmaz
      Aug 12 '18 at 19:50











    • $begingroup$
      There aren't such cases, I tried the solution above and it was accepted.
      $endgroup$
      – user158037
      Oct 12 '18 at 16:07
















    • $begingroup$
      This is a great solution but it fails if the numbers are not consecutive. To illustrate; 1 3 5 2 4 6 8 does not pass this test case @Rainer P.
      $endgroup$
      – Ugur Yilmaz
      Aug 12 '18 at 17:25







    • 1




      $begingroup$
      @UgurYilmaz - Your question literaly says [...] consisting of consecutive integers [...].
      $endgroup$
      – Rainer P.
      Aug 12 '18 at 18:55











    • $begingroup$
      I know but there should be an error in hackerRank, then. Because there is a test case with that input and it seems to fail. Do you have any idea how to implement a solution efficiently if it is not a consecutive array integers @Rainer P.
      $endgroup$
      – Ugur Yilmaz
      Aug 12 '18 at 19:50











    • $begingroup$
      There aren't such cases, I tried the solution above and it was accepted.
      $endgroup$
      – user158037
      Oct 12 '18 at 16:07















    $begingroup$
    This is a great solution but it fails if the numbers are not consecutive. To illustrate; 1 3 5 2 4 6 8 does not pass this test case @Rainer P.
    $endgroup$
    – Ugur Yilmaz
    Aug 12 '18 at 17:25





    $begingroup$
    This is a great solution but it fails if the numbers are not consecutive. To illustrate; 1 3 5 2 4 6 8 does not pass this test case @Rainer P.
    $endgroup$
    – Ugur Yilmaz
    Aug 12 '18 at 17:25





    1




    1




    $begingroup$
    @UgurYilmaz - Your question literaly says [...] consisting of consecutive integers [...].
    $endgroup$
    – Rainer P.
    Aug 12 '18 at 18:55





    $begingroup$
    @UgurYilmaz - Your question literaly says [...] consisting of consecutive integers [...].
    $endgroup$
    – Rainer P.
    Aug 12 '18 at 18:55













    $begingroup$
    I know but there should be an error in hackerRank, then. Because there is a test case with that input and it seems to fail. Do you have any idea how to implement a solution efficiently if it is not a consecutive array integers @Rainer P.
    $endgroup$
    – Ugur Yilmaz
    Aug 12 '18 at 19:50





    $begingroup$
    I know but there should be an error in hackerRank, then. Because there is a test case with that input and it seems to fail. Do you have any idea how to implement a solution efficiently if it is not a consecutive array integers @Rainer P.
    $endgroup$
    – Ugur Yilmaz
    Aug 12 '18 at 19:50













    $begingroup$
    There aren't such cases, I tried the solution above and it was accepted.
    $endgroup$
    – user158037
    Oct 12 '18 at 16:07




    $begingroup$
    There aren't such cases, I tried the solution above and it was accepted.
    $endgroup$
    – user158037
    Oct 12 '18 at 16:07













    0












    $begingroup$

    The fastest way so far I tried is



    1. For each iteration of "i"

    2. Try to find out from the list ( i - 1, arr.length ) if there is an item misplaced

    3. If there is an misplaced item, swap it




    const minimalSwap = (arr) => 
    // don't mutate the original array
    let list = [...arr]
    // length of the list
    const listLen = list.length
    // state - total swap
    let totalSwap = 0
    if (listLen <= 1)
    return totalSwap

    function swap(items, idxOne, idxTwo)
    let tempNode = items[idxOne]
    items[idxOne] = items[idxTwo]
    items[idxTwo] = tempNode
    totalSwap += 1
    return items

    for (let i = 0; i < listLen; i++)
    // for each iteration, we find the
    // number that should go to the correct position
    let idToSwap = false
    const correctNumber = i + 1
    // iterate through starting next item
    // and find if the correct number is misplaced
    for (let j = i + 1; j < listLen; j++)
    // if it is misplaced, swap it
    if (correctNumber === list[j])
    idToSwap = j
    break;


    if (idToSwap)
    list = swap(list, i, idToSwap)



    return totalSwap


    // test case
    minimalSwap([14, 15, 16, 4, 8, 3, 1, 2, 5, 7, 9, 10, 11, 12, 13, 6])







    share








    New contributor




    R.R is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
    Check out our Code of Conduct.






    $endgroup$

















      0












      $begingroup$

      The fastest way so far I tried is



      1. For each iteration of "i"

      2. Try to find out from the list ( i - 1, arr.length ) if there is an item misplaced

      3. If there is an misplaced item, swap it




      const minimalSwap = (arr) => 
      // don't mutate the original array
      let list = [...arr]
      // length of the list
      const listLen = list.length
      // state - total swap
      let totalSwap = 0
      if (listLen <= 1)
      return totalSwap

      function swap(items, idxOne, idxTwo)
      let tempNode = items[idxOne]
      items[idxOne] = items[idxTwo]
      items[idxTwo] = tempNode
      totalSwap += 1
      return items

      for (let i = 0; i < listLen; i++)
      // for each iteration, we find the
      // number that should go to the correct position
      let idToSwap = false
      const correctNumber = i + 1
      // iterate through starting next item
      // and find if the correct number is misplaced
      for (let j = i + 1; j < listLen; j++)
      // if it is misplaced, swap it
      if (correctNumber === list[j])
      idToSwap = j
      break;


      if (idToSwap)
      list = swap(list, i, idToSwap)



      return totalSwap


      // test case
      minimalSwap([14, 15, 16, 4, 8, 3, 1, 2, 5, 7, 9, 10, 11, 12, 13, 6])







      share








      New contributor




      R.R is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.






      $endgroup$















        0












        0








        0





        $begingroup$

        The fastest way so far I tried is



        1. For each iteration of "i"

        2. Try to find out from the list ( i - 1, arr.length ) if there is an item misplaced

        3. If there is an misplaced item, swap it




        const minimalSwap = (arr) => 
        // don't mutate the original array
        let list = [...arr]
        // length of the list
        const listLen = list.length
        // state - total swap
        let totalSwap = 0
        if (listLen <= 1)
        return totalSwap

        function swap(items, idxOne, idxTwo)
        let tempNode = items[idxOne]
        items[idxOne] = items[idxTwo]
        items[idxTwo] = tempNode
        totalSwap += 1
        return items

        for (let i = 0; i < listLen; i++)
        // for each iteration, we find the
        // number that should go to the correct position
        let idToSwap = false
        const correctNumber = i + 1
        // iterate through starting next item
        // and find if the correct number is misplaced
        for (let j = i + 1; j < listLen; j++)
        // if it is misplaced, swap it
        if (correctNumber === list[j])
        idToSwap = j
        break;


        if (idToSwap)
        list = swap(list, i, idToSwap)



        return totalSwap


        // test case
        minimalSwap([14, 15, 16, 4, 8, 3, 1, 2, 5, 7, 9, 10, 11, 12, 13, 6])







        share








        New contributor




        R.R is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
        Check out our Code of Conduct.






        $endgroup$



        The fastest way so far I tried is



        1. For each iteration of "i"

        2. Try to find out from the list ( i - 1, arr.length ) if there is an item misplaced

        3. If there is an misplaced item, swap it




        const minimalSwap = (arr) => 
        // don't mutate the original array
        let list = [...arr]
        // length of the list
        const listLen = list.length
        // state - total swap
        let totalSwap = 0
        if (listLen <= 1)
        return totalSwap

        function swap(items, idxOne, idxTwo)
        let tempNode = items[idxOne]
        items[idxOne] = items[idxTwo]
        items[idxTwo] = tempNode
        totalSwap += 1
        return items

        for (let i = 0; i < listLen; i++)
        // for each iteration, we find the
        // number that should go to the correct position
        let idToSwap = false
        const correctNumber = i + 1
        // iterate through starting next item
        // and find if the correct number is misplaced
        for (let j = i + 1; j < listLen; j++)
        // if it is misplaced, swap it
        if (correctNumber === list[j])
        idToSwap = j
        break;


        if (idToSwap)
        list = swap(list, i, idToSwap)



        return totalSwap


        // test case
        minimalSwap([14, 15, 16, 4, 8, 3, 1, 2, 5, 7, 9, 10, 11, 12, 13, 6])








        const minimalSwap = (arr) => 
        // don't mutate the original array
        let list = [...arr]
        // length of the list
        const listLen = list.length
        // state - total swap
        let totalSwap = 0
        if (listLen <= 1)
        return totalSwap

        function swap(items, idxOne, idxTwo)
        let tempNode = items[idxOne]
        items[idxOne] = items[idxTwo]
        items[idxTwo] = tempNode
        totalSwap += 1
        return items

        for (let i = 0; i < listLen; i++)
        // for each iteration, we find the
        // number that should go to the correct position
        let idToSwap = false
        const correctNumber = i + 1
        // iterate through starting next item
        // and find if the correct number is misplaced
        for (let j = i + 1; j < listLen; j++)
        // if it is misplaced, swap it
        if (correctNumber === list[j])
        idToSwap = j
        break;


        if (idToSwap)
        list = swap(list, i, idToSwap)



        return totalSwap


        // test case
        minimalSwap([14, 15, 16, 4, 8, 3, 1, 2, 5, 7, 9, 10, 11, 12, 13, 6])





        const minimalSwap = (arr) => 
        // don't mutate the original array
        let list = [...arr]
        // length of the list
        const listLen = list.length
        // state - total swap
        let totalSwap = 0
        if (listLen <= 1)
        return totalSwap

        function swap(items, idxOne, idxTwo)
        let tempNode = items[idxOne]
        items[idxOne] = items[idxTwo]
        items[idxTwo] = tempNode
        totalSwap += 1
        return items

        for (let i = 0; i < listLen; i++)
        // for each iteration, we find the
        // number that should go to the correct position
        let idToSwap = false
        const correctNumber = i + 1
        // iterate through starting next item
        // and find if the correct number is misplaced
        for (let j = i + 1; j < listLen; j++)
        // if it is misplaced, swap it
        if (correctNumber === list[j])
        idToSwap = j
        break;


        if (idToSwap)
        list = swap(list, i, idToSwap)



        return totalSwap


        // test case
        minimalSwap([14, 15, 16, 4, 8, 3, 1, 2, 5, 7, 9, 10, 11, 12, 13, 6])





        share








        New contributor




        R.R is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
        Check out our Code of Conduct.








        share


        share






        New contributor




        R.R is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
        Check out our Code of Conduct.









        answered 8 mins ago









        R.RR.R

        101




        101




        New contributor




        R.R is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
        Check out our Code of Conduct.





        New contributor





        R.R is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
        Check out our Code of Conduct.






        R.R is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
        Check out our Code of Conduct.



























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Code Review Stack Exchange!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            Use MathJax to format equations. MathJax reference.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f201470%2fminimum-swaps-algorithm-terminated-due-to-timeout%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            名間水力發電廠 目录 沿革 設施 鄰近設施 註釋 外部連結 导航菜单23°50′10″N 120°42′41″E / 23.83611°N 120.71139°E / 23.83611; 120.7113923°50′10″N 120°42′41″E / 23.83611°N 120.71139°E / 23.83611; 120.71139計畫概要原始内容臺灣第一座BOT 模式開發的水力發電廠-名間水力電廠名間水力發電廠 水利署首件BOT案原始内容《小檔案》名間電廠 首座BOT水力發電廠原始内容名間電廠BOT - 經濟部水利署中區水資源局

            Prove that NP is closed under karp reduction?Space(n) not closed under Karp reductions - what about NTime(n)?Class P is closed under rotation?Prove or disprove that $NL$ is closed under polynomial many-one reductions$mathbfNC_2$ is closed under log-space reductionOn Karp reductionwhen can I know if a class (complexity) is closed under reduction (cook/karp)Check if class $PSPACE$ is closed under polyonomially space reductionIs NPSPACE also closed under polynomial-time reduction and under log-space reduction?Prove PSPACE is closed under complement?Prove PSPACE is closed under union?

            Is my guitar’s action too high? Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern)Strings too stiff on a recently purchased acoustic guitar | Cort AD880CEIs the action of my guitar really high?Μy little finger is too weak to play guitarWith guitar, how long should I give my fingers to strengthen / callous?When playing a fret the guitar sounds mutedPlaying (Barre) chords up the guitar neckI think my guitar strings are wound too tight and I can't play barre chordsF barre chord on an SG guitarHow to find to the right strings of a barre chord by feel?High action on higher fret on my steel acoustic guitar