Sequence Numbering Within Grouped Records
SQL & DataAuto-graded · 16 test casesLast updated
Tests ability to assign sequential positions to records within partitions using sorting and grouping logic.
You are given a list of entry records. Each entry belongs to a conversation identified by context_uuid. Your task is to assign each entry a sequential position number within its conversation.
Each entry is represented as a dictionary with these fields:
entry_uuid: unique identifier for the entrycontext_uuid: identifier for the conversation containing this entryvisitor_id: identifier for the visitor who created the entrycreated_at: timestamp when the entry was createdplatform: platform where the entry was created
Numbering Rules:
- Position numbers start at 1 within each distinct
context_uuid - Within a conversation, entries are ordered by
created_atin ascending order - If two entries have identical
created_atvalues, order them byentry_uuidin ascending order - Null values in sort keys should be treated as smaller than any non-null value (appear first)
Return a new list where each entry dictionary includes an additional entry_number field containing its position. The fields in each output dictionary must appear in this exact order: entry_uuid, context_uuid, visitor_id, created_at, platform, entry_number.
The output list may be in any order.
Constraints:
- 0 ≤ number of entries ≤ 10,000
entry_uuid,context_uuid,visitor_id,created_at, andplatformmay beNone- Timestamps are ISO 8601 strings when present
- All fields are either strings or
None
Examples
Example 1
Input: assign_entry_positions([{'entry_uuid': 'e1', 'context_uuid': 'c1', 'visitor_id': 'v1', 'created_at': '2024-01-01T10:00:00', 'platform': 'web'}, {'entry_uuid': 'e2', 'context_uuid': 'c1', 'visitor_id': 'v1', 'created_at': '2024-01-01T10:01:00', 'platform': 'mobile'}, {'entry_uuid': 'e3', 'context_uuid': 'c2', 'visitor_id': 'v2', 'created_at': '2024-01-01T09:00:00', 'platform': 'web'}])
Output: [{'entry_uuid': 'e1', 'context_uuid': 'c1', 'visitor_id': 'v1', 'created_at': '2024-01-01T10:00:00', 'platform': 'web', 'entry_number': 1}, {'entry_uuid': 'e2', 'context_uuid': 'c1', 'visitor_id': 'v1', 'created_at': '2024-01-01T10:01:00', 'platform': 'mobile', 'entry_number': 2}, {'entry_uuid': 'e3', 'context_uuid': 'c2', 'visitor_id': 'v2', 'created_at': '2024-01-01T09:00:00', 'platform': 'web', 'entry_number': 1}]
Example 2
Input: assign_entry_positions([{'entry_uuid': 'b', 'context_uuid': 'c1', 'visitor_id': 'v1', 'created_at': '2024-01-01T10:00:00', 'platform': 'web'}, {'entry_uuid': 'a', 'context_uuid': 'c1', 'visitor_id': 'v2', 'created_at': '2024-01-01T10:00:00', 'platform': 'mobile'}])
Output: [{'entry_uuid': 'a', 'context_uuid': 'c1', 'visitor_id': 'v2', 'created_at': '2024-01-01T10:00:00', 'platform': 'mobile', 'entry_number': 1}, {'entry_uuid': 'b', 'context_uuid': 'c1', 'visitor_id': 'v1', 'created_at': '2024-01-01T10:00:00', 'platform': 'web', 'entry_number': 2}]
Hints
Hint 1
Think about how you would group entries by conversation and then order them within each group.
Hint 2
Sorting by multiple keys where nulls come first requires careful handling of None values in Python.
Hint 3
A single pass through sorted data with a counter per group is sufficient - no need for nested loops.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem requires assigning consecutive position numbers to entries within their respective conversations. The core challenge is implementing per-group sequential numbering with a specific ordering.
The solution works in two phases:
- Sort all entries to group them by conversation and order them correctly within each group
- Traverse the sorted list once, maintaining a counter for each conversation
Sorting Strategy:
Sort by three keys in order: context_uuid, then created_at, then entry_uuid. This places all entries from the same conversation together and orders them by the specified rules.
Null Handling:
Python cannot directly compare None with strings. The sort key (x is not None, x or '') handles this by:
- First comparing booleans:
False < True, soNonevalues (which giveFalse) sort before non-null values - Then comparing the actual values (or empty string for
None)
This ensures nulls appear first in each sort dimension.
Position Assignment:
After sorting, a single pass assigns positions. A dictionary tracks the current count for each context_uuid. For each entry, increment its conversation's counter and use that as the position number.
Why This Works
- Sorting by
context_uuidgroups all entries from the same conversation contiguously - Within each group, the
created_atandentry_uuidkeys establish the required ordering - Since entries are already in the correct order, a simple counter per group produces the right position numbers
- The null-sorting technique ensures deterministic behavior matching the specification
Complexity
- Time: O(n log n) for sorting, where n is the number of entries. The traversal is O(n).
- Space: O(n) for the output list and O(k) for the counter dictionary, where k is the number of distinct conversations. Overall O(n).
Solution
from typing import List, Dict
def assign_entry_positions(entries: List[Dict]) -> List[Dict]:
# Sort by context, then timestamp, then entry ID; None sorts first
ordered = sorted(
entries,
key=lambda e: (
e['context_uuid'] is not None, e['context_uuid'] or '',
e['created_at'] is not None, e['created_at'] or '',
e['entry_uuid'] is not None, e['entry_uuid'] or ''
)
)
counts = {} # Track position counter per conversation
result = []
for entry in ordered:
context = entry['context_uuid']
counts[context] = counts.get(context, 0) + 1
result.append({
'entry_uuid': entry['entry_uuid'],
'context_uuid': context,
'visitor_id': entry['visitor_id'],
'created_at': entry['created_at'],
'platform': entry['platform'],
'entry_number': counts[context]
})
return result