// Challenge: remove duplicate elements from a list.
// Input: [1, 2, 2, 3, 3, 3, 4]
// Expected output: [1, 2, 3, 4]
// Solution 1: using a Set.
// A Set does not allow duplicates, so converting to a Set and back
// to a List removes them all at once. It's the most idiomatic way in Dart.
List<T> removeDuplicates<T>(List<T> list) {
return list.toSet().toList();
}
// Solution 2: by hand, to explain the logic in an interview.
// We iterate and only add what we haven't seen yet.
List<T> removeDuplicatesManual<T>(List<T> list) {
final seen = <T>{};
final result = <T>[];
for (final element in list) {
if (!seen.contains(element)) {
seen.add(element);
result.add(element);
}
}
return result;
}
void main() {
print(removeDuplicates([1, 2, 2, 3, 3, 3, 4])); // [1, 2, 3, 4]
print(removeDuplicates(['a', 'b', 'a', 'c'])); // [a, b, c]
print(removeDuplicatesManual([1, 1, 1])); // [1]
print(removeDuplicatesManual<int>([])); // [] (edge case)
// Explanation:
// The Set version is the shortest, but it doesn't guarantee order
// in all cases (although in practice Dart keeps insertion order).
// The manual version keeps the order explicitly and makes the "how" clear.
// The <T> makes the functions generic: they work for lists of any type.
}