Search code examples
javascriptarraysalgorithmdata-structuressequence

Find Repeat Sequence in an Array


I encountered a problem and have tried many solutions, but none have worked. Given an array of numbers [3, 2, 16, 16, 15, 1, 2, 16, 16, 16, 15, 1, 2], I would like to discover the repeated sequence in this array.

The expected output should be [16, 16, 15, 1, 2].


Solution

  • You could take two nested loops and check the first and second same values with an offset for a sequence.

    function longest(array) {
       let result = [];
       for (let i = 0; i < array.length - 1; i++) {
           for (let j = i + 1; j < array.length; j++) {
               let offset = 0;
               for (; offset + j < array.length; offset++) {
                   if (array[i + offset] !== array[j + offset]) break;
               }
               if (result.length < offset) result = array.slice(i, i + offset);
           }   
       }
       return result;
    }
    
    console.log(longest([3, 2, 16, 16, 15, 1, 2, 16, 16, 16, 15, 1, 2]));