Remove duplicate elements from an array, preserving order. Uses a set for O(1) lookups on hashable items and falls back to linear search for unhashable items. Args: array: Input list potentially containing duplicates. Returns: New list with duplicates removed, orig
(array: list[Any])
| 18 | |
| 19 | |
| 20 | def remove_duplicates(array: list[Any]) -> list[Any]: |
| 21 | """Remove duplicate elements from an array, preserving order. |
| 22 | |
| 23 | Uses a set for O(1) lookups on hashable items and falls back to |
| 24 | linear search for unhashable items. |
| 25 | |
| 26 | Args: |
| 27 | array: Input list potentially containing duplicates. |
| 28 | |
| 29 | Returns: |
| 30 | New list with duplicates removed, original order preserved. |
| 31 | |
| 32 | Examples: |
| 33 | >>> remove_duplicates([1, 1, 2, 2, 3]) |
| 34 | [1, 2, 3] |
| 35 | """ |
| 36 | seen = set() |
| 37 | unique_array = [] |
| 38 | |
| 39 | for item in array: |
| 40 | if isinstance(item, Hashable): |
| 41 | if item not in seen: |
| 42 | seen.add(item) |
| 43 | unique_array.append(item) |
| 44 | else: |
| 45 | if item not in unique_array: |
| 46 | unique_array.append(item) |
| 47 | |
| 48 | return unique_array |