KatInterview

Order-Preserving Unique Values from a Mixed List

Arrays & HashingAuto-graded · 22 test cases
EasyAuto-gradedArrays & Hashinghash-setordered-dictarrays

Last updated

Tests using a hash-based structure to drop repeated values from a list while keeping first-occurrence order, in linear time and without modifying the input.

Order-Preserving Unique Values

You receive a list whose items are simple values: integers or strings. Build and return a new list that holds each distinct value exactly once.

The values in the result must be arranged in the order in which they first showed up in the input. Any later repeat of a value is discarded.

The input list must remain unchanged.

Details

  • Two values count as the same only if they are equal under Python's normal == and hashing rules. For example, the integer 1 and the string "1" are different values.
  • If the input is empty, return an empty list.
  • The result must be a different list object from the input, even when all values are already distinct.
  • Aim for O(n) average time, where n is the length of the input, using O(n) extra space.

Constraints

  • The list may contain integers, strings, or a mix of both.
  • The list length is at most 1,000,000.
  • Every item is a primitive value (no nested lists, dicts, or custom objects).

Examples

Example 1

Input: unique_in_order([1, 2, 2, 3, 4, 1, 5])

Output: [1, 2, 3, 4, 5]

Example 2

Input: unique_in_order(['apple', 'orange', 'apple', 'banana', 'orange'])

Output: ['apple', 'orange', 'banana']

Hints

Hint 1

Checking whether a value already exists in the output list is O(n) per check and leads to O(n^2) overall. Use a structure with O(1) average membership tests.

Hint 2

A set tells you whether a value was seen, but a set alone does not keep order. Combine a set with an output list, appended to only on the first sighting.

Hint 3

Python dicts remember insertion order, and inserting an existing key does not move it. Think about how to build a dict from the input and read its keys back.