Skip to content

Instantly share code, notes, and snippets.

@Wajahat-Jawaid
Last active September 23, 2018 09:07
Show Gist options
  • Save Wajahat-Jawaid/b5fb1d7141476f2a20115d33d4954bf4 to your computer and use it in GitHub Desktop.
Save Wajahat-Jawaid/b5fb1d7141476f2a20115d33d4954bf4 to your computer and use it in GitHub Desktop.
package com;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class RocketLogics {
/** Please refer to https://gist.github.com/Wajahat-Jawaid/815da29116c18223ec365a3db745cea5
* for the test cases as multiple gists couldn't be linked */
public static void main(String[] args) {
// Arbitrary array.
Object[] objArray = new Object[] {1, 4, new Object[] {43,434,34,2}, 3, new Object[]{1, 3, 4}};
RocketLogics rocket = new RocketLogics();
NestedArrayFlattener flattener = rocket.new NestedArrayFlattener();
final Integer[] intArray = flattener.flatten(objArray);
}
class NestedArrayFlattener {
/**
* This method flattens an arbitrarily nested array of integers to return the flattened integer array.
*
* @param objArray an array of Integers or nested arrays of Integers
* @return flattened array of Integers or null if input is null
* @throws IllegalArgumentException
*/
public Integer[] flatten(Object[] objArray) throws IllegalArgumentException {
// If objArray is null, then no need to parse
if (objArray == null) return null;
// We can put the custom condition which handles Big O notation. But that totally depends upon the scenario
List<Integer> flattenedIntegers = new ArrayList<Integer>();
for (Object item : objArray) {
if (item instanceof Integer) {
flattenedIntegers.add((Integer) item);
} else if (item instanceof Object[]) {
// If nested array is found, perform recursion
flattenedIntegers.addAll(Arrays.asList(flatten((Object[]) item)));
} else {
throw new IllegalArgumentException("Input array can contain only integer or nested integer array");
}
}
return flattenedIntegers.toArray(new Integer[flattenedIntegers.size()]);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment