Keep First Occurrence of Each Element
Arrays & HashingAuto-graded · 17 test casesLast updated
Tests understanding of hash-based deduplication while maintaining insertion order in a single pass through an array.
Write a function that removes repeated elements from an array, keeping only the first occurrence of each unique value in its original position.
Your function should accept an integer array and return a new array containing each distinct element exactly once, preserving the order in which values first appeared in the input.
Task
Given an array of integers, produce a new array where:
- Each value appears at most once
- The relative order matches the position of each value's first appearance in the input
- Later repetitions of the same value are omitted
Constraints
- The input array is never null or undefined
0 ≤ array length ≤ 200,000- Each integer value satisfies
-1,000,000,000 ≤ value ≤ 1,000,000,000 - Two integers are considered duplicates if and only if they are numerically equal
- Do not reorder the output by sorting or any other criterion
- Target linear time complexity relative to input size
Examples
Example 1
Input: keep_first_occurrences([7, 6, 4, 3, 3, 4, 9])
Output: [7, 6, 4, 3, 9]
Example 2
Input: keep_first_occurrences([0, -1, 0, -1, 2])
Output: [0, -1, 2]
Hints
Hint 1
Use a data structure that provides fast membership testing to track which values you've already included in the output
Hint 2
A set can tell you in constant time whether you've seen a value before, while a list preserves the insertion order
Hint 3
Process the array from left to right, adding each value to your result only if it hasn't been encountered yet
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The solution maintains two complementary data structures during a single left-to-right scan:
- A hash set to track which values have already been added to the output
- A list to accumulate the deduplicated values in their first-appearance order
For each element in the input, check whether it exists in the tracking set. If not present, this is the element's first occurrence—add it to both the set and the output list. If already present, skip it entirely since an earlier position already captured this value.
The set provides constant-time membership queries, while the list naturally maintains insertion order. Neither structure alone solves both requirements: sets lack ordering guarantees, and lists have linear-time membership checks that would make the overall algorithm quadratic.
Why This Works
Consider the loop invariant: after processing the first i elements, the output list contains each distinct value from that prefix exactly once, ordered by first appearance, and the set contains precisely those same distinct values.
Initially, both structures are empty, satisfying the invariant trivially. At each step, if the current value is new (not in the set), it's genuinely the first time we've encountered it, so appending it preserves first-appearance order. If the value already exists in the set, an earlier iteration already placed it in the output at its correct position, so skipping maintains correctness.
When the loop completes, the invariant holds for the entire input array, which means the output is correct.
Complexity
Time: O(n) expected, where n is the input length. Each element requires one set membership check and at most one set insertion plus one list append. Python's hash set operations run in expected constant time for integer keys in this value range.
Space: O(u) additional memory, where u is the number of distinct values (at most n). Both the set and the output list grow to size u. Since the output is required by the problem specification, the actual overhead is just the set.
Edge Cases
- Empty array returns an empty array
- Single-element array returns a copy of that array
- Array with all identical values returns a single-element array
- Array with all distinct values returns a copy in the same order
- Negative values and zero are handled correctly (avoid truthiness checks like
if not value) - Maximum constraint values (±1 billion) work without overflow in Python
Common Mistakes
Converting to a set and back with list(set(nums)) loses order because sets are unordered. Using value not in result for membership checking produces correct output but degrades to O(n²) time with many distinct values, causing timeouts on large inputs. Sorting the deduplicated values violates the order-preservation requirement.
Solution Code
from typing import List
def keep_first_occurrences(nums: List[int]) -> List[int]:
seen = set()
result = []
for value in nums:
if value not in seen:
seen.add(value)
result.append(value)
return result