Menu

Sign in to track your progress and unlock all features.

Theme style

Log in
01. Count unique elementsE02. Remove duplicates from a listE03. Check if an array contains duplicatesE

Problem No 2

Remove duplicates from a list

Easy

8 minute session

Summary

Return a new list with duplicates removed while preserving the original order.

Problem statement

Given a list arr, implement remove_duplicates(arr) which returns a new list containing the elements of arr with duplicates removed. The relative order of the first occurrences must be preserved. Use a set to track seen elements to achieve O(n) average time. The function should handle empty input and different repetition patterns.

Task

Implement remove_duplicates(arr) to eliminate repeated values but keep the first occurrence order using a set to track seen values.

Examples

Preserve order

Input

remove_duplicates([1, 2, 2, 3, 1])

Output

[1, 2, 3]

Explanation

First occurrences are 1, then 2, then 3. Later repeats are removed.

Input format

A list of hashable elements (e.g., integers): [1, 2, 2, 3, 1]

Output format

A list with duplicates removed, preserving the first occurrence order.

Constraints

0 <= len(arr) <= 10^5. Elements are hashable. Aim for O(n) average time and O(n) extra space.

Samples

Sample input 0

[3, 1, 3, 2, 1]

Sample output 0

[3, 1, 2]

Explanation 0

Keep first occurrences in their original order.

Code editor
Loading editor…

AI assistant

Ask me anything!

Need help? I can explain the core idea behind this problem, review your current code, and give targeted hints. Use “Teach Theory” for the concept, “Get AI hint” for a quick scaffold nudge, or ask a specific question below.

Chat history is temporary and will not be saved.

03:43 PM

Free preview includes 1 Teach Theory response and 1 AI hint on each of the first 3 lessons in this module.