KatInterview

Keep Only First Appearances in an Integer List

Arrays & HashingAuto-graded · 21 test cases
EasyAuto-gradedArrays & Hashinghash-setarraysdeduplication

Last updated

Tests using a hash set alongside a list to filter repeated integers in one pass while preserving first-appearance order, in linear time.

Keep Only First Appearances

You are given a list of integers values. Build and return a new list that keeps each distinct integer exactly once, at the position of its first appearance in values. Every later copy of an integer is discarded. The surviving integers must keep the same relative order they had in the input.

The input list must not be modified; return a new list.

Rules

  • If values is empty, return an empty list.
  • If every integer is already distinct, the result has the same contents and order as the input.
  • If all integers are equal, the result contains that integer exactly once.
  • Negative numbers and zero are ordinary integers and are compared by value.
  • Do not sort the data: sorting would destroy the order that must be preserved.

Constraints

  • 0 <= len(values) <= 1,000,000
  • -10^9 <= values[i] <= 10^9
  • Target time complexity: O(n) expected, where n is the length of the list.
  • Target extra space: O(u), where u is the number of distinct integers.

Examples

Example 1

Input: keep_first_occurrences([4, 5, 4, 1, 2, 5])

Output: [4, 5, 1, 2]

Example 2

Input: keep_first_occurrences([1, 1, 1, 1])

Output: [1]

Example 3

Input: keep_first_occurrences([])

Output: []

Hints

Hint 1

Walk through the list once from left to right and decide for each element whether it has appeared before.

Hint 2

Checking membership in a list is a linear scan, which can make the whole algorithm quadratic. Use a structure with constant-time expected lookups for the values already seen.

Hint 3

Keep two things: a set of values seen so far, and an output list. Append a value to the output (and add it to the set) only when it is not yet in the set.