Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You can construct the "difference" strings <code>S</code> and <code>S'</code>, i.e. a string which contains the characters at the differing positions of the two strings, e.g. for <code>acbacb</code> and <code>abcabc</code> it will be <code>cbcb</code> and <code>bcbc</code>. Let us say this contains n characters.</p> <p>You can now construct a "permutation graph" G which will have <code>n</code> nodes and an edge from <code>i</code> to <code>j</code> if <code>S[i] == S'[j]</code>. In the case of all unique characters, it is easy to see that the required number of swaps will be (n - number of cycles in G), which can be found out in O(n) time.</p> <p>However, in the case where there are any number of duplicate characters, this reduces to the problem of finding out the largest number of cycles in a directed graph, which, I think, is NP-hard, (e.g. check out: <a href="http://www.math.ucsd.edu/~jverstra/dcig.pdf" rel="nofollow noreferrer">http://www.math.ucsd.edu/~jverstra/dcig.pdf</a> ).</p> <p>In that paper a few greedy algorithms are pointed out, one of which is particularly simple:</p> <ol> <li>At each step, find the minimum length cycle in the graph (e.g. <a href="https://stackoverflow.com/questions/3911626/find-cycle-of-shortest-length-in-a-directed-graph-with-positive-weights">Find cycle of shortest length in a directed graph with positive weights</a> )</li> <li>Delete it</li> <li>Repeat until all vertexes have not been covered.</li> </ol> <p>However, there may be efficient algorithms utilizing the properties of your case (the only one I can think of is that your graphs will be K-partite, where K is the number of unique characters in <code>S</code>). Good luck!</p> <p>Edit: Please refer to David's answer for a fuller and correct explanation of the problem.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload