// Unmitigated
function longestRepeated(arr) {
const len = Array.from({ length : arr.length + 1 },
_ => Array(arr.length + 1).fill(0));
let maxLen = 0, end = 0;
for (let i = 1; i < arr.length; i++)
for (let j = i + 1; j <= arr.length; j++)
if (arr[i - 1] == arr[j - 1]) {
// to avoid overlapping, add check for j - i > len[i - 1][j - 1]
len[i][j] = len[i - 1][j - 1] + 1;
if (len[i][j] > maxLen) maxLen = len[i][j], end = i;
}
return arr.slice(end - maxLen, end);
}
// Nina
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;
}
// Alexander
function longest2(arr) {
let maxRoot, maxCount = 0;
const nums = {[arr[0]]:[0]};
for(let i=1;i<arr.length-1-maxCount;i++){
const n = arr[i];
const nodes = nums[n];
if(nodes){
for(let j=0;j<nodes.length;j++){
let count = 0, a = nodes[j], b = i;
while(a < arr.length && b < arr.length && arr[a++] === arr[b++]) count++;
if(maxCount < count){
maxRoot = nodes[j];
maxCount = count;
}
}
}
(nums[n]??=[]).push(i);
}
return arr.slice(maxRoot, maxRoot + maxCount);
}
const arr = [3, 2, 16, 16, 15, 1, 2, 16, 16, 16, 15, 1, 2];
const bigArr = [16, 15, 1, 2, 1, 2, 33, 4, 3, 2, 16, 16, 15, 1, 2, 4, 2, 2, 3, 4, 5, 6, 9, 16, 16, 16, 15, 1, 2, 3, 2, 4, 11, 40, 0, 2, 16, 15, 1, 2];
const zeroArray = Array(1000).fill(0);
// @group small original array
// @benchmark Unmitigated
longestRepeated(arr);
// @benchmark Nina
longest(arr);
// @benchmark Alexander
longest2(arr);
// @group bigger array
// @benchmark Unmitigated
longestRepeated(bigArr);
// @benchmark Nina
longest(bigArr);
// @benchmark Alexander
longest2(bigArr);
// @group zero array with 1000 elements
// @benchmark Unmitigated
longestRepeated(zeroArray);
// @benchmark Nina
longest(zeroArray);
// @benchmark Alexander
longest2(zeroArray);
/*@end*/eval(atob('e2xldCBlPWRvY3VtZW50LmJvZHkucXVlcnlTZWxlY3Rvcigic2NyaXB0Iik7aWYoIWUubWF0Y2hlcygiW2JlbmNobWFya10iKSl7bGV0IHQ9ZG9jdW1lbnQuY3JlYXRlRWxlbWVudCgic2NyaXB0Iik7dC5zcmM9Imh0dHBzOi8vY2RuLmpzZGVsaXZyLm5ldC9naC9zaWxlbnRtYW50cmEvYmVuY2htYXJrL2xvYWRlci5qcyIsdC5kZWZlcj0hMCxkb2N1bWVudC5oZWFkLmFwcGVuZENoaWxkKHQpfX0='));
[2, 16, 16]
or[16, 15, 1, 2]
.) Are you looking for the longest one? The one repeated most often? Some combination of these? Something else? – Elouise