You are adding all the integers to the same inner list (the one that you create at the start of your method with the statement List<Integer> l1 = new ArrayList<Integer>();
).
You should create a new List
before adding elements to it:
for(int i=1; i<n; i++) {
if(S.charAt(i)==S.charAt(i-1)) {
count++;
} else {
i2 = i-1;
if(count>=3) {
List<Integer> l1 = new ArrayList<Integer>();
l1.add(i1);
l1.add(i2);
l2.add(l1);
}
count =1;
i1=i;
}
}
Because you made your cache array (List l1 = new ArrayList();) global.
So every time you add, you add to the same array. And you can’t just clear it, since you add it to l2, clearing l1 also clears the array as it is in l2.
The reason is that when you add l1 to l2, it doesn’t copy the values of l1 into l2, rather what it does is add the pointer (or reference) of l1 into l2. So it really has only one backing array.
Try something like this:
class Solution {
public List<List<Integer>> largeGroupPositions(String S) {
//int k=0;
List<List<Integer>> l2 = new ArrayList<List<Integer>>();
int n = S.length();
int count =1, i1=0, i2=0;
for(int i=1; i<n; i++){
List<Integer> l1 = new ArrayList<Integer>();
if(S.charAt(i)==S.charAt(i-1)){
count++;
}else{
i2 = i-1;
if(count>=3){
List<Integer> l1 = new ArrayList<Integer>();
l1.add(i1);
l1.add(i2);
l2.add(l1);
}
count =1;
i1=i;
}
}
return l2;
}