Search code examples
algorithmdynamic-programmingarray-algorithms

Shortest subsequence with no interval duplicates


Given an unsorted array of N integers and a function getNextIndexOf(int k) that returns the index of the next element whose value is 'k', how would one get at the last element (i.e., index N) with the fewest number of calls to getNextIndexOf(int k) ?

*In other words, with what values k1, k2, ... , km should one call getNextIndexOf(int k) so that the mth call returns 'N', and m is as small as possible?

**Edit: you can assume getNextIndexOf can keep track of the last index it returns
(e.g., like a static local variable in C). The very first call it just returns the index of the first element equal to its argument (int k).


Solution

  • A possible solution (written in Java!):

    public static List<Integer> getShortest(int[] array) 
    {
       int[] nextChoice = new int[array.length];
       HashMap<Integer,Integer> readable = new HashMap<Integer,Integer>();
    
       readable.put(Integer(array[array.length-1]), Integer(array.length-1));
       for(int i = array.length-1; i>=0; i--)
       {
          for(Map.Entry<Integer,Integer> entry: readable.entrySet())
          {
             if(entry.getValue().intValue() > nextChoice[i])
                nextChoice[i] = entry.getKey();
          }
          readable.put(Integer(array[i]),i);
       }
    
       List<Integer> shortestList = new LinkedList<Integer>(array.length);
       for(int i = 0; i < array.length; i++)
          shortestList.add(nextChoice[i]);
    
       return shortestList;
    }