JSFiddle - React, Tailwind, and code Playground
by Anonymous
HTML
<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.22.1/ramda.min.js"></script>
JavaScript
// Design an algorithm that takes a sequence of n document words and a sequence of m query
// words and find the shortest interval in which the m query words appear in the document in
// the order given. The length of an interval is the number of words in that interval.
const _ = R;
const memoizedFSPBT = _.memoize(findShortestPathBetweenTerms);
function findShortestPathBetweenTerms(documents, terms, startIndex = 0) {
let currentSearchTerm = terms[0];
let j = 0;
let length = 0;
let nextLength = Infinity;
for (let i = startIndex; i < documents.length; i++) {
if (documents[i] == terms[0] && j > 0) {
let temp = memoizedFSPBT(documents, terms, i);
if (temp < nextLength) {
nextLength = temp;
}
}
if (j < terms.length) {
if (currentSearchTerm === documents[i]){
currentSearchTerm = terms[++j];
length++;
} else if (j > 0) {
length++;
}
}
}
if (j >= terms.length) { return length > nextLength ? nextLength : length; }
else { return nextLength; }
}
const result = memoizedFSPBT([0,2,4,5,6,324,234,6,235,34,1,5,6,2,3,7,2,3,3,7,2], [6,7,2,3]);
console.log(result);