KatInterview

Keep First Occurrence of Each Element

Arrays & HashingAuto-graded · 17 test cases
MediumAuto-gradedArrays & Hashingarrayshash-setdeduplication

Last 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