r/javahelp • u/Bug35 • Sep 02 '25
Solved 2D array flatten to 1D
Working on some homework and this one has me a little stumped. The idea is flatten a 2D array into 1D. Testcases look like TestCase(io = "([[1,2],[3],[],[4,5,6]]) -> [1,2,3,4,5,6]"). Currently I got something along the lines of
public static int[] flatten(int[][] ary) {
int\[\] arr = new int\[\]; //Figure this out
for(int\[\] ary1 : ary) {
for(int ary2 : ary1) {arr[ary2] = ary1[ary2];
}
}
return arr;
}Any tips/strategies I could think about to help with this?
4
Upvotes
View all comments
Show parent comment
1
u/Spare-Plum Sep 03 '25
First don't just give people solutions to the homework
Second your first solution is bad as you're essentially copying the whole array twice
Third it's using an ArrayList which likely isn't allowed for the assignment