recently solving a data structure question and counter below question
Given an integer array, find the largest subarray formed by consecutive integers. The subarray should contain all distinct values.
2 set of examples as below
input = [2, 0, 2, 1, 4, 3, 0, 0]; // Output: The largest subarray is [ 0, 2, 1, 4, 3 ]
input= [2, 0, 2, 0, 4, 3, 0, 0]; // Output: The largest subarray is [2, 0, 4, 3]
below is my implementation but its seems me too naïve and complex , someone suggest me how to optimize it
const largestSubArray = (arr) => {
// first check whether array have any suplicate value
const hasDuplicate = arr.some((a, i, arr) => arr.indexOf(a) !== i);
// console.log({hasDuplicate});
if (!hasDuplicate) {
return arr;
} else {
const indexedArray = [];
for (let i = 0; i < arr.length; i++) {
let curr = arr[i];
for (let j = i + 1; j < arr.length; j++) {
let next = arr[j];
// if having duplicate value then set the index of both element in indexedArray
if (next === curr) {
indexedArray.push([i, j]);
break;
}
// if reach end of array and found no duplicate value
if (j === arr.length - 1) {
indexedArray.push([i, j]);
}
}
}
// console.log({indexedArray});
// create new array which hold difference between duplicate value index position
let op = [];
for (const [i, j] of indexedArray) {
const diff = j - i;
op.push(diff);
}
// find maximum differnce value
const maxx = Math.max(...op);
const mIndex = op.indexOf(maxx);
// retrive maximum diffrence array from indexedArray
const [min, max] = indexedArray[mIndex];
const output = arr.slice(min, max);
// recursively call for next found array for the same
return largestSubArray(output);
}
};
const inputArray1 = [2, 0, 2, 1, 4, 3, 0, 0];
const result1 = largestSubArray(inputArray1);
const inputArray2 = [2, 0, 2, 0, 4, 3, 0, 0];
const result2 = largestSubArray(inputArray2);
console.log({
result1,
result2
});
[2, 0, 4, 3]
leads to a definition a subarray whose values are unique/distinct; consecutive is a bit strong as 1 is missing, and no order. \$\endgroup\$[2, 0, 2, 0, 4, 3, 0, 0]
you'll get candidates[2, 0], [0, 2], [2, 0, 4, 3], [4, 3, 0], [0]
, so with rewinding. Should be rather simple. \$\endgroup\$