KatInterview

Keep First Record Per Login ID in Linear Time

Arrays & HashingAuto-graded · 18 test cases
EasyAuto-gradedArrays & Hashinghash-setdeduplicationarrays

Last updated

Filter a list of record dictionaries so only the first record for each identifier remains, preserving order and doing it in a single linear pass with a hash set.

Problem

A dashboard receives a large list of login-record dictionaries. Each record looks like this:

  • "sessionId": a string that identifies the login
  • "timestamp": an integer
  • "data": an arbitrary payload, possibly large (a string, a nested dictionary, etc.)

The same sessionId can show up several times. Write a function that removes the repeats so that each sessionId appears exactly once in the output.

Rules

  • For every distinct sessionId, keep only the first record in the input that has it. Discard all later records with that ID.
  • The surviving records must stay in the same relative order they had in the input.
  • Two records are duplicates if and only if their sessionId values are equal. timestamp and data play no part in the comparison.
  • The returned records must be the original dictionary objects from the input. Do not copy or modify them.
  • Every record is guaranteed to contain a "sessionId" key.
  • An empty input returns an empty list.

The straightforward approach of checking each record against everything kept so far is quadratic and too slow for large inputs. Your solution should run in linear time on average.

Constraints

  • 0 <= len(sessions) <= 100000
  • Each record has the keys "sessionId" (string), "timestamp" (integer), and "data" (any value).
  • data may be large, so avoid copying records.
  • Target time complexity: O(n) on average.

Examples

Example 1

Input: keep_first_per_id([{'sessionId': 's1', 'timestamp': 100, 'data': {'role': 'admin'}}, {'sessionId': 's2', 'timestamp': 200, 'data': 'metadata'}, {'sessionId': 's1', 'timestamp': 300, 'data': {'role': 'user'}}])

Output: [{'sessionId': 's1', 'timestamp': 100, 'data': {'role': 'admin'}}, {'sessionId': 's2', 'timestamp': 200, 'data': 'metadata'}]

Example 2

Input: keep_first_per_id([{'sessionId': 'only', 'timestamp': 1, 'data': 'large payload'}])

Output: [{'sessionId': 'only', 'timestamp': 1, 'data': 'large payload'}]

Hints

Hint 1

Checking whether an ID was already kept by scanning the output list costs O(n) per record. What structure answers 'have I seen this key?' in O(1) on average?

Hint 2

Walk the input once, from left to right. Keep a set of IDs already emitted, and append a record to the output only when its ID is not yet in the set.

Hint 3

Store only the ID strings in the set and append the original dictionaries (references) to the result. This keeps memory low and preserves input order automatically.