Skip to main content

Find the longest sequence of numbers in an Array where each number is unique

 Ex:-  [1, 2, 1, 3, 2, 7 ,4, 2]

in the give array longest sequence that contain unique numbers is 1, 3, 2, 7 ,4.

Hence the required answer is 5 (no. of unique numbers ).

Java


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
 import java.util.*;
 public class LongestSequence{
     public static void main(String []args){
        int[] arr = { 1, 2, 1, 3, 2, 7 ,4, 2 };
        HashSet hs = new HashSet();
        int count = 0, mlsf = 0; // mlsf - maximum length so far
        for(int i=0; i<arr.length; i++){
            if(hs.add(arr[i])){
                mlsf ++ ;
            }
            else{
                count = Math.max(mlsf, count);
                hs.clear(); //delete all elements of hashset
                hs.add(arr[i]);
                mlsf = 1;
            }
        }
        System.out.println(count);
     }
 }

Python


arr = [1, 2, 1, 3, 2, 7 ,4, 2]
mlsf, ans = 0, 0 # mlsf - max length so far
s = set()   
for i in arr:
    pl = len(s) # pl- previous length
    s.add(i)
    if(len(s)>pl):
        mlsf += 1
    else:
        ans = max(ans, mlsf)
        s.clear()  # delete all elements of set
        s.add(i)
        mlsf = 1
print(ans)