0
     public static int[] longestSeq(int[] a) {
       int longestSeq = 1;
       int longestInd = 0;
       for (int i = 0; i < a.length-1; i++) {
         int counter = 1;
         while (a[i] == a[i + 1]){
           counter++;
           i++;
         }
         if (counter > longestSeq){
           longestSeq = counter;
           longestInd = i;
         }
       }
       return new int[] {longestSeq, longestInd};
     }

What is the error? The code is trying to find out the longest contiguous sequence in an array of integers. What could be a way to do that?

aks
  • 1

1 Answers1

2

It could go out of bounds in your while loop, where you are directly accessing i+1 without bound checks

while(i < a.length - 1 && a[i] == a[i + 1]){
     counter++;
     i++;
}
Rajan Kali
  • 12,627
  • 3
  • 25
  • 37
  • That is not the only problem though. Also using i is not correct. i controls the for loop so a new counter variable (int j=i) has to be introduced. – geanakuch Feb 20 '21 at 08:18