Easy 0 solved 0% acceptance

Remove Duplicates

Keep only the first occurrence of each value.

What you'll learn

  • Track seen values with a set
  • Keep the first occurrence of each value
  • Preserve the original order

Problem

Return the list with repeated values removed, keeping the first occurrence of each value in its original order.

Implement remove_duplicates(numbers).

Input

numbers: The list of integers.

Output

Return the list without duplicates.

Constraints

0 ≤ length ≤ 100,000

Examples

Example 1
Input:
numbers = [3, 1, 3, 2, 1]

Expected output:
expected = [3, 1, 2]
Input:
std::vector<long long> numbers = {3, 1, 3, 2, 1};

Expected output:
std::vector<long long> expected = {3, 1, 2};
Input:
long[] numbers = new long[] {3, 1, 3, 2, 1};

Expected output:
long[] expected = new long[] {3, 1, 2};

Explanation

Keep 3, 1, then 2; the later 3 and 1 are dropped: [3, 1, 2].

Example 2
Input:
numbers = [7, 7, 7]

Expected output:
expected = [7]
Input:
std::vector<long long> numbers = {7, 7, 7};

Expected output:
std::vector<long long> expected = {7};
Input:
long[] numbers = new long[] {7, 7, 7};

Expected output:
long[] expected = new long[] {7};

Explanation

Only the first 7 stays: [7].

How to approach it

Try on your own first, then open one hint at a time.

Hint 1

Keep the first time each value appears and ignore later repeats.

Hint 2

A set or similar lookup helps you decide quickly whether a value was already seen.

Hint 3

Preserve the original order of the first occurrences, not sorted order.

Expected complexity

O(n) time, O(n) extra space

References

This challenge is adapted for CodeUtility. Follow the statement and constraints above.

Learn from others

Community solutions

No published solutions yet. Solve this challenge to share the first one.