You are given an array A of N integers. Return a 2D array consisting of all the subarrays of the array.
I had tried to get subarrays in temp as per loop and add that subarray directly to ans(2d arraylist)
public ArrayList<ArrayList<Integer>> solve(ArrayList<Integer> A) {
int n=A.size();
ArrayList<ArrayList<Integer>> ans= new ArrayList<>();
for(int i=0;i<n;i++)
{
ArrayList<Integer> temp=new ArrayList<>();
for(int j=i;j<n;j++)
{
temp.add(A.get(j));
ans.add(temp);
}
}
return ans;
}
Input: [1,2,3,4,5]
Output: [1 2 3 4 5 ] [1 2 3 4 5 ] [1 2 3 4 5 ] [1 2 3 4 5 ] [1 2 3 4 5 ] [2 3 4 5 ] [2 3 4 5 ] [2 3 4 5 ] [2 3 4 5 ] [3 4 5 ] [3 4 5 ] [3 4 5 ] [4 5 ] [4 5 ] [5 ]
Expected output: [[1],[1,2],[1,2,3],[1,2,3,4],[1,2,3,4,5],[2],[2,3],[2,3,4],[2,3,4,5],[3],[3,4],[3,4,5],[4],[4,5],[5]]
The issue is that you're adding the same
ArrayListobject (temp) multiple times toans. In Java, theArrayListobject is mutable. So, when you modifytemp, all the references to it inansget updated as well.To fix, create a new list from
tempbefore adding it toans, e.g., usenew ArrayList<>(temp):Output: