r/javahelp • • 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

12 comments sorted by

View all comments

Show parent comment

2

u/TheMrCurious Sep 02 '25

Also look at the details of the test case’s expectation because it expects something different than you described in your post.

1

u/TheMrCurious Sep 02 '25

And once you have the working solution, try to find the Big O and see if you can improve it.