Keep First Record Per Login ID in Linear Time
Arrays & HashingAuto-graded · 18 test casesLast 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
sessionIdvalues are equal.timestampanddataplay 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). datamay 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.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The slow version keeps an output list and, for every incoming record, scans that list looking for the same sessionId. In the worst case (all IDs unique) this performs about n(n-1)/2 comparisons, which is O(n²). For 100,000 records that is roughly 5 billion comparisons.
The fix is to use a better structure for the "have I seen this ID?" question. A hash set answers it in O(1) on average.
- Create an empty set
seenfor IDs and an empty listresult. - Iterate over the input once, in order.
- Read the record's
sessionIdonce. - If the ID is not in
seen, add it toseenand append the record toresult. - Otherwise skip the record.
- Return
result.
Why it is correct
After processing the first k records, seen contains exactly the distinct IDs among them, and result contains the first record for each of those IDs in input order. When record k+1 has a new ID, it is the first occurrence, so it is appended at the end, which keeps the order correct. When its ID is already in seen, a earlier record with that ID was kept, so this one is a later duplicate and is correctly dropped. By induction, the final output is exactly the first occurrence of every ID in original order.
Because only references are appended, the records are never copied, so large data payloads cost no extra memory.
Complexity
- Time: O(n) on average, one pass with O(1) average set lookups and inserts.
- Space: O(u), where u is the number of distinct IDs. The set holds u ID strings and the result holds u references.
Edge cases
- Empty input returns
[]. - All records sharing one ID returns a list with only the first record.
- All unique IDs returns every record in the original order.
Reference solution
from typing import Dict, List
def keep_first_per_id(sessions: List[Dict]) -> List[Dict]:
seen = set()
result = []
for session in sessions:
session_id = session["sessionId"]
if session_id not in seen:
seen.add(session_id)
result.append(session)
return result