Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Problem No 16

Get unique elements preserving order

Medium

16 minute session

Summary

Return the unique elements from a list while keeping their first-seen order.

Problem statement

Write a function unique_preserve(lst) that takes a list and returns a new list with only the first occurrence of each element, preserving the original order. Do not use sorting. The function should handle any hashable elements (numbers, strings, tuples) and must preserve the order in which distinct elements first appear.

Task

Learn how to remove duplicates from a list without changing the relative order of first occurrences.

Examples

Basic example

Input

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

Output

[1, 2, 3]

Explanation

1 appears first, then 2, then 3. Subsequent duplicates are ignored.

Input format

A single list (e.g., [1, 2, 2, 3]) passed to unique_preserve.

Output format

A list containing the first occurrence of each distinct element, in original order.

Constraints

You may assume elements are hashable. Do not change the input list in-place (return a new list). Aim for O(n) time and O(n) extra space.

Samples

Sample input 0

unique_preserve([5, 5, 6, 7, 6])

Sample output 0

[5, 6, 7]

Explanation 0

Keeps first 5, first 6, and first 7; ignores later duplicates.

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.

09:06 PM

Free preview includes 1 Teach Theory response and 1 AI hint per unlocked preview lesson.