// Challenge: flatten a nested list (turn lists within lists into a single one).
// Input: [1, [2, 3], [4, [5, 6]]]
// Expected output: [1, 2, 3, 4, 5, 6]
// Solution: recursion.
// We walk through each element; if it's a list, we flatten it too
// (calling ourselves) and add its elements.
List<int> flatten(List<dynamic> list) {
final result = <int>[];
for (final element in list) {
if (element is List) {
// It's a sublist: we flatten it recursively.
result.addAll(flatten(element));
} else if (element is int) {
result.add(element);
}
}
return result;
}
void main() {
print(flatten([1, [2, 3], [4, [5, 6]]])); // [1, 2, 3, 4, 5, 6]
print(flatten([[1], [2], [3]])); // [1, 2, 3]
print(flatten([1, 2, 3])); // [1, 2, 3] (already flat)
print(flatten([])); // [] (edge case)
// Explanation:
// Recursion is the key: when we find a list inside the list, we call
// flatten on it again. That works no matter how many levels of nesting
// there are. The "is" operator checks the type at runtime to decide
// whether we flatten or add.
}