Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Here's a simple algorithm which scans the array once, constantly checking if its currently-seen covering range is shorter than the previously seen covering ranges.</p> <p>For simplicity, I'm going to assume that we can map A, B, C, D, and E to the integers 0-4 so that we can easily reference an array. I haven't checked it thoroughly, so please mentally/actually run it on an example or two to make sure it does what you want.</p> <pre><code>//Cell 0 is the last index at which we saw an A, cell 1 " " saw a B, etc. int[] mostRecent = new int[U.length]; mostRecent.setAllValsTo(POSITIVE_INFINITY); int shortestRange = POSITIVE_INFINITY; //We are trying to minimize this number. int minIndex = 0; //The beginning index of the range int maxIndex = POSITIVE_INFINITY; //The ending index of the range. for(int i=0; i&lt; S.length; i++) { int currentValue = S[i]; //This value will be 0-4, corresponding to A-E mostRecent[currentValue] = i; currentMax = mostRecent.findMax(); //beginning of current range currentMin = mostRecent.findMin(); //end of current range currentRange = currentMax - currentMin; if(currentRange &lt; shortestRange) { shortestRange = currentRage; minIndex = currentMin; maxIndex = currentMax; } } //currentMax and currentMin now carry the starting and ending indices, use them as you see fit. return shortestRange; </code></pre> <p>This is order O(nk), with n=S.length and k=U.length. There are still plenty of optimizations to squeeze out of it, but I don't know if I could bring the worst-case order lower.</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. VO
      singulars
      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