Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the shortest path in one dimension

Tags:

algorithm

In the one dimensional array S , There might be any number of elements that belong to the set

U:{A,B,C,D,E}  

and repetition is allowed.
Example :

S  = {E,B,D,C,A,D,A,E,E,D,B,B,A,C} 

Question is:

What is the most efficient way in which I can determine the shortest range/path that contains all the elements belonging to set U ,In any given array S ? keep in mind the array can't be sorted.

In the above example the shortest path is that connecting the first 5 elements of the array S.

EDIT :
1) The Number Of Elements of set U isn't constant.

Thanks in advance.

like image 829
Adham Atta Avatar asked Apr 13 '11 13:04

Adham Atta


1 Answers

Interesting homework, but you still have to code yourself.

Good thing is you have not told us which language you use, so I take it as a sign as you've decided to code yourself, which is good.


My best try so far:

Have 2 pointers for the sub string (range), one for the start (smaller index) of the range and one for the end (larger index). Both point to the beginning of the array first.

Have a list for how many ABCDEs are in the range respectively.

Iterate end from left to right.

For every character, increment the number for the character in the list. If the result (incremented how many) > 1(, see if start points to the same character. If yes, move start forward and minus 1, and) while start points to a character the related number for which > 1, move start forward and minus 1.

If ABCDE in the list all >= 1, then we've found a candidate range. Compare it to the shortest length (if any), and if it is smaller, update the shortest length and record the index for the start of the new shortest range.

like image 186
Dante May Code Avatar answered Sep 18 '22 15:09

Dante May Code