Skip to content

Commit

Permalink
updating method signature in flatten array
Browse files Browse the repository at this point in the history
  • Loading branch information
jagdish-15 committed Jan 4, 2025
1 parent 919b7f7 commit fb2e4ba
Show file tree
Hide file tree
Showing 3 changed files with 11 additions and 21 deletions.
1 change: 1 addition & 0 deletions exercises/practice/flatten-array/.meta/config.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
"aadityakulkarni",
"FridaTveit",
"jackattack24",
"jagdish-15",
"jmrunkle",
"jtigger",
"kytrinyx",
Expand Down
Original file line number Diff line number Diff line change
@@ -1,28 +1,17 @@
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

final class Flattener {
class Flattener {

List flatten(final List nestedList) {
if (nestedList.isEmpty()) {
return new ArrayList<>();
} else {
final List result = new ArrayList();

final Object head = nestedList.get(0);
final List tail = nestedList.subList(1, nestedList.size());

if (head instanceof List) {
result.addAll(flatten((List) head));
} else {
result.add(head);
List<Object> flatten(List<?> list) {
List<Object> flattenedList = new ArrayList<>();
for (Object element: list) {
if (element instanceof List<?> listAsElement) {
flattenedList.addAll(flatten(listAsElement));
} else if (element != null) {
flattenedList.add(element);
}

result.addAll(flatten(tail));
result.removeAll(Collections.singleton(null));
return result;
}
return flattenedList;
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

class Flattener {

<T> List<T> flatten(List<T> list) {
List<Object> flatten(List<?> list) {
throw new UnsupportedOperationException("Delete this statement and write your own implementation.");
}

Expand Down

0 comments on commit fb2e4ba

Please sign in to comment.