First of all, we could somewhat limit the operations using the following observation: if we found some unique sequence, then we don't have to check any sequence which is shorter. So we iterate j in [i+ans, n]
.
Next, if we know that uniqueness breaks for sequence from i
to j
, we don't have to expand it any further - we know that no longer sequence with i
as start would be unique. So on the else
statement of your check we just break the inner loop.
This way the iterations count seems to be something like O(n)
, since the j
index will never go back.
upd: About the Ishpreet's answer (since I can't comment yet, I'll post it here).
This code won't work properly for sequences where the longest subsequence is not the first one. For example, consider this array: [2,3,4,3,1,5,2]
. The correct answer would be 5
- the length of 4,3,1,5,2
; but the answer given by the code above will be 3
. The reason is that this code essentially drops all the sequence collected before the first duplicate came, which is not what we need, since we could take the part after the first duplicating number, including the second (which is not duplicating now) - like in this example.
Furthermore, this approach suffers from one fundamental problem. If we don't store (or otherwise check) the duplicate position, we can't know if it ever interfere with currently found subsequence, and so we don't know how much exactly we must drop (and do we need at all). It might be way before current subsequence started, shadowed by another duplicate; or it may be just here, in the previous number, forcing us to start anything from scratch.
Here's a piece of code trying to cover these cases (but it is yet to check its full correctness):
var map = {}
var arr = [2,3,4,4,5,1,6,2,8,5,9,3];
var ans = 1, currentSeqLength = 0;
for(var i=0; i<arr.length; i++){
if(arr[i] in map && map[arr[i]] >= i - currentSeqLength) {
currentSeqLength -= map[arr[i]];
} else {
currentSeqLength++;
}
map[arr[i]] = i;
ans = Math.max(ans, currentSeqLength);
}
console.log(ans); // 6 i.e. Length of 4,5,1,6,2,8