Iterative Nested List Flattening and UTC Active User Metrics
SQL & DataModel answerLast updated
Implement an iterative nested list flattener in Python with edge-case handling, and construct a SQL query to compute Daily Active Users (DAU) using strict UTC date casting.
You are asked to solve two distinct data processing tasks common in software engineering and data platform engineering interviews.
Task 1: Python Iterative List Flattening
Write a function flatten(nested) in Python that accepts a input containing integers or deeply nested lists of integers, returning a flattened list of integers preserving left-to-right element order.
Requirements
- Iterative Design: Avoid reliance on recursive function calls to prevent stack overflow errors when encountering heavily nested inputs (e.g., nesting depth $\ge 10^4$).
- Type Enforcement: Only integers (excluding booleans) and lists are valid data elements. Raise a
TypeErrorif non-list types are passed at the top level, or if any invalid types (such as floats, strings,None, dictionaries, or boolean values) are encountered during traversal. - Complexity & Testing:
- Define the Big-O time and space complexity of your implementation.
- Provide explicit test coverage demonstrating correctness for empty lists, extreme nesting depths, invalid types, and cyclic list references.
Task 2: SQL Daily Active Users (DAU) Calculation
Given a database table named events with the following schema:
| Column Name | Data Type | Description |
|---|---|---|
user_id | INT | Unique identifier for the user |
event_time | TIMESTAMP or TIMESTAMPTZ | Timestamp when the action occurred |
event_type | VARCHAR | Description of the action (e.g., 'click', 'login') |
Write an ANSI SQL compliant query that calculates the Daily Active Users (DAU) for each UTC calendar date.
Requirements
- UTC Uniformity: Ensure timestamps are explicitly evaluated in UTC, guarding against unexpected session time-zone shifts.
- Deduplication: A user who triggers multiple events within the same UTC calendar day must only be counted once for that date.
- Output: Return two columns named
event_dateanddau, ordered chronologically byevent_date.
Hints
Hint 1
For the Python flattening task, maintaining an explicit stack of iterators (using `iter()`) allows depth-first traversal without copying list items onto the stack ahead of time.
Hint 2
Remember that in Python, `isinstance(True, int)` evaluates to `True`. You must explicitly disallow `bool` instances if only raw integers are allowed.
Hint 3
In SQL, casting a timezone-aware timestamp directly to a `DATE` can yield different results depending on the database session time zone. Use explicit `AT TIME ZONE 'UTC'` clauses.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Task 1: Python Implementation & Analysis
Algorithmic Strategy
Using standard recursion in Python for tree-like traversals risks triggering a RecursionError due to the default recursion ceiling (~1,000 frames). To handle lists nested $10^4$ levels deep, we maintain an explicit call stack using Python's iterator abstraction (iter()).
- Iterator Stack: Instead of dumping list elements directly onto an execution stack (which requires reverse insertion to preserve left-to-right ordering), we maintain a stack of iterators representing the path from the root list down to the current active sublist.
- Traversal: In each iteration, we fetch the next item via
next(stack[-1]):- If a sublist is encountered, push
iter(sublist)onto the stack. - If an integer is encountered (and verified not to be a
bool), append it to the result vector. - If the top iterator raises
StopIteration, pop it from the stack to backtrack.
- If a sublist is encountered, push
- Cycle Detection: To prevent infinite loops caused by circular structures (
lst.append(lst)), keep a set of Python object identifiers (id()) for lists currently along the active stack path.
from typing import Any, List
def flatten(nested: List[Any]) -> List[int]:
"""
Flattens a nested structure of lists and integers into a single flat list.
Raises:
TypeError: If top-level input is not a list or if an invalid element type is found.
ValueError: If a cyclic reference is detected.
"""
if not isinstance(nested, list):
raise TypeError(f"Top-level input must be a list, got {type(nested).__name__}")
flattened: List[int] = []
# Active path iterator stack and cycle tracker
iterator_stack = [iter(nested)]
active_list_ids = {id(nested)}
list_stack = [nested]
while iterator_stack:
try:
item = next(iterator_stack[-1])
except StopIteration:
iterator_stack.pop()
active_list_ids.discard(id(list_stack.pop()))
continue
if isinstance(item, list):
item_id = id(item)
if item_id in active_list_ids:
raise ValueError("Cyclic list reference detected.")
active_list_ids.add(item_id)
list_stack.append(item)
iterator_stack.append(iter(item))
# Note: bool is a subclass of int in Python, so explicit type checking is required
elif isinstance(item, int) and not isinstance(item, bool):
flattened.append(item)
else:
raise TypeError(
f"Invalid item found: {item!r} of type {type(item).__name__}"
)
return flattened
# ---- Verification Test Suite ----
def run_tests():
# 1. Basic & Nested Lists
assert flatten([1, [2, [3, 4], 5], [[6]], 7]) == [1, 2, 3, 4, 5, 6, 7]
# 2. Empty Inputs
assert flatten([]) == []
assert flatten([[], [[]], [[[]]]]) == []
# 3. Deep Nesting Test (10,000 Levels)
deep_list: list = [99]
for _ in range(10_000):
deep_list = [deep_list]
assert flatten(deep_list) == [99]
# 4. Shared Acyclic References (valid, should non-destructively process both)
shared = [10, 20]
assert flatten([shared, 5, shared]) == [10, 20, 5, 10, 20]
# 5. Invalid Element Types
invalid_cases = ["str", 3.14, None, True, False, {"key": "val"}]
for bad in invalid_cases:
try:
flatten([1, [bad]])
assert False, f"Failed to raise TypeError for {bad}"
except TypeError:
pass
# 6. Cycle Handling
cyclic: list = [1, 2]
cyclic.append(cyclic)
try:
flatten(cyclic)
assert False, "Failed to raise ValueError for cyclic list"
except ValueError:
pass
print("All Python tests executed successfully.")
if __name__ == "__main__":
run_tests()
Complexity Analysis
- Time Complexity: $\mathcal{O}(N)$, where $N$ is the total count of elements (integers and sublist objects combined) across all nesting depths. Every list object and scalar value is retrieved via iterator steps exactly once.
- Space Complexity: $\mathcal{O}(D + K)$, where $D$ represents the maximum nesting depth (size of stack tracking iterators and active list IDs) and $K$ represents the total number of integer outputs returned. Excluding output storage, the auxiliary overhead is $\mathcal{O}(D)$.
Task 2: SQL Aggregation Query
SQL Approach
Computing DAU relies on two key operations:
- Converting event timestamps to a standardized UTC date component.
- Counting distinct
user_idvalues per calendar day.
If event_time is stored as a timezone-aware timestamp (TIMESTAMPTZ), evaluating event_time::DATE directly will use the database server's local session timezone, potentially shifting midnight boundaries. Applying AT TIME ZONE 'UTC' forces the conversion into a fixed UTC timestamp before truncating to DATE.
SELECT
CAST(event_time AT TIME ZONE 'UTC' AS DATE) AS event_date,
COUNT(DISTINCT user_id) AS dau
FROM events
WHERE user_id IS NOT NULL
AND event_time IS NOT NULL
GROUP BY 1
ORDER BY event_date ASC;
Common Pitfalls & Alternative Engines
-
Naive Timestamps (
TIMESTAMP WITHOUT TIME ZONE): If the column values are already stored as raw UTC timestamps without embedded timezone metadata, applyingAT TIME ZONE 'UTC'in PostgreSQL converts the timestamp from UTC to local time, producing offset errors. For naive UTC timestamps, cast directly:CAST(event_time AS DATE) AS event_date -
Performance Scaling (Large Datasets / Distributed DBs): In distributed engines like Snowflake, Presto, or Spark SQL,
COUNT(DISTINCT user_id)can cause memory bottlenecks on reducer nodes due to global shuffle steps. An equivalent alternative is pre-deduplicating using a subquery or Common Table Expression (CTE):WITH daily_user_activity AS ( SELECT DISTINCT CAST(event_time AT TIME ZONE 'UTC' AS DATE) AS event_date, user_id FROM events WHERE user_id IS NOT NULL ) SELECT event_date, COUNT(*) AS dau FROM daily_user_activity GROUP BY event_date ORDER BY event_date ASC;