Build a CSV Data Frame and Assembly of Sequence Fragments
Data Structure DesignModel answerLast updated
Parse RFC 4180 CSV into an in-memory table with query support, and reconstruct chained sequences from directed or undirected overlapping fragments.
This task consists of two distinct components. Implement a solution for both parts.
Part 1: In-Memory CSV Data Frame
Design an in-memory data frame class initialized from a CSV-formatted string.
Requirements:
- Parse the raw input string yourself without using third-party libraries or native CSV modules (e.g., Python's
csvmodule). - The initial line specifies column headers; subsequent lines contain row values.
- Your parser must handle RFC 4180 rules:
- Comma-delimited values.
- Empty values (e.g.,
a,,bor trailing commas). - Quoted values enclosed in double quotes (
"..."). - Escaped double quotes inside quoted fields represented as pair quotes (
""). - Embedded line breaks (
\nor\r\n) within quoted fields. - Commas inside quoted fields.
- Raise an exception for invalid formatting (e.g., unclosed quotes, characters immediately following a closing quote without a separator, inconsistent column counts, or duplicate header names).
- Expose a retrieval method
select(columns=None, predicate=None):columns: optional list of column names to return. IfNone, return all columns.predicate: optional filter function applied to each row dict. Returns rows wherepredicate(row)is true.- Preserves original row insertion order.
Part 2: Reconstruction of Overlapping Sequences
You are given a list of sequence fragments. Each fragment object contains three properties: start, end, and payload. The end string of one segment matches the start string of another segment.
Base Task:
Given a list of fragments that form a single non-branching directed path (one start head, one terminal end), assemble and return the concatenated payload strings in proper sequential order.
Example:
[
{"start": "bbb", "end": "ccc", "payload": "1"},
{"start": "aaa", "end": "bbb", "payload": "2"},
{"start": "ccc", "end": "ddd", "payload": "3"}
]
The connected chain is aaa -> bbb -> ccc -> ddd, yielding the payload order ["2", "1", "3"]. Output: "213".
Follow-up Scenarios:
- Undirected Fragments: The endpoints for each fragment are given as an unordered pair
(u, v)along withpayload. Reconstruct the full ordered sequence of payloads. - Multiple Chains & Validation: The input may contain disconnected valid chains, isolated loops, or branching errors. Write logic to detect and separate all distinct linear sequences, and identify malformed topologies (such as branching nodes with degree > 2 or unexpected cycles).
Hints
Hint 1
For CSV parsing, use a state machine tracking whether you are currently inside quotes and whether the previous character closed a quote.
Hint 2
In Part 2 base problem, identify the head of the chain by looking for a start node whose string key never appears as any fragment's end node.
Hint 3
For undirected fragments, think of endpoints as vertices and fragments as edges. Vertices with degree 1 must be sequence endpoints; interior vertices must have degree 2.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach Walkthrough
Part 1: In-Memory CSV Data Frame
Parsing Strategy
Splitting strings directly via str.split(',') or str.split('\n') fails when fields contain commas or line breaks wrapped in quotation marks. Instead, we use a single-pass character state machine.
We maintain:
in_quotes: flag indicating if the iterator is currently inside a double-quoted block.after_quote: flag indicating that a double quote was just closed. The only valid next characters are,,\r,\n, or EOF.field_buf: list of characters for the current field.row_buf: list of parsed fields for the current record.
Error Handling Strategy
- Unclosed Quote:
in_quotesremainsTrueat EOF. - Malformed Escape: Character appears after a closing quote before a delimiter (e.g.,
"abc"def). - Quote inside Unquoted Field: Unescaped quote appears mid-field without starting at the boundary (e.g.,
ab"cd). - Row Length Mismatch: Number of elements in a row does not match header count.
- Duplicate Headers: Columns contain duplicate labels.
Query Design
select(columns, predicate) iterates over rows, evaluating predicate(row_dict). If true, it extracts desired key-value pairs into a new dictionary.
class DataFrame:
def __init__(self, raw_csv: str):
parsed_rows = self._parse_csv(raw_csv)
if not parsed_rows:
raise ValueError("CSV input is empty.")
self.headers = parsed_rows[0]
if len(self.headers) != len(set(self.headers)):
raise ValueError("Duplicate header columns detected.")
self.rows = []
num_cols = len(self.headers)
for idx, row in enumerate(parsed_rows[1:], start=2):
if len(row) != num_cols:
raise ValueError(f"Line {idx}: Expected {num_cols} values, got {len(row)}.")
self.rows.append(dict(zip(self.headers, row)))
def _parse_csv(self, text: str):
rows = []
current_row = []
field = []
in_quotes = False
after_quote = False
i = 0
n = len(text)
while i < n:
ch = text[i]
if in_quotes:
if ch == '"':
# Escaped quote check ("")
if i + 1 < n and text[i + 1] == '"':
field.append('"')
i += 1
else:
in_quotes = False
after_quote = True
else:
field.append(ch)
else:
if ch == ',':
current_row.append(''.join(field))
field = []
after_quote = False
elif ch in ('\r', '\n'):
# Handle \r\n
if ch == '\r' and i + 1 < n and text[i + 1] == '\n':
i += 1
current_row.append(''.join(field))
rows.append(current_row)
current_row = []
field = []
after_quote = False
elif after_quote:
raise ValueError(f"Invalid character '{ch}' following closing quote at index {i}.")
elif ch == '"':
if field:
raise ValueError(f"Unexpected quote inside unquoted field at index {i}.")
in_quotes = True
else:
field.append(ch)
i += 1
if in_quotes:
raise ValueError("Unclosed quoted field at end of input.")
# Capture remaining field if text does not end with newline
if field or current_row or after_quote:
current_row.append(''.join(field))
rows.append(current_row)
return rows
def select(self, columns=None, predicate=None):
target_cols = self.headers if columns is None else columns
for c in target_cols:
if c not in self.headers:
raise KeyError(f"Column '{c}' does not exist.")
result = []
for row in self.rows:
if predicate is None or predicate(row):
result.append({c: row[c] for c in target_cols})
return result
Part 2: Reconstruction of Overlapping Sequences
Base Solution: Directed Path Assembly
Each fragment is a directed edge $u \to v$.
- Build a map
start_map: start_node -> fragment. - Collect all
endnodes into a setall_ends. - The chain start head is the unique node present in
start_mapbut missing fromall_ends. - Traverse from
headsequentially by jumping tofragment['end'].
def assemble_directed_chain(fragments):
if not fragments:
return ""
start_map = {f['start']: f for f in fragments}
all_ends = {f['end'] for f in fragments}
heads = [s for s in start_map if s not in all_ends]
if len(heads) != 1 or len(start_map) != len(fragments):
raise ValueError("Fragments do not form a single continuous linear chain.")
curr = heads[0]
payloads = []
while curr in start_map:
frag = start_map[curr]
payloads.append(frag['payload'])
curr = frag['end']
if len(payloads) != len(fragments):
raise ValueError("Chain contains cycles or isolated fragments.")
return "".join(payloads)
Follow-ups: Undirected Edges & Multiple Chains
When endpoints (u, v) are undirected edges:
- Degree Constraints: For valid linear chains, inner endpoints must have degree 2; terminal endpoints must have degree 1.
- Multiple Disjoint Paths: Run an Euler-path-style walk starting from each unvisited degree-1 vertex.
- Validation Rules:
- Nodes with degree $> 2$ indicate branching (invalid).
- Nodes with odd degree non-equal to 1 indicate improper structures.
- Connected components with no degree-1 vertices contain closed cycles (invalid).
from collections import defaultdict
def assemble_undirected_chains(fragments):
"""
Assembles multiple undirected fragments into linear chains.
Returns a list of payload sequences (one string per valid linear chain).
Raises ValueError if cycles or branching structures are detected.
"""
adj = defaultdict(list)
edge_visited = set()
for idx, f in enumerate(fragments):
u, v = f['endpoint_a'], f['endpoint_b']
payload = f['payload']
adj[u].append((v, idx, payload))
adj[v].append((u, idx, payload))
# Validate degrees
for node, edges in adj.items():
if len(edges) > 2:
raise ValueError(f"Branching detected at node '{node}' with degree {len(edges)}.")
chains = []
# 1. Traverse all linear chains starting from endpoints (degree == 1)
for start_node in adj:
if len(adj[start_node]) == 1:
# Check if edge already traversed from other direction
edge_info = adj[start_node][0]
if edge_info[1] in edge_visited:
continue
curr_node = start_node
chain_payloads = []
while True:
# Find an unvisited edge from curr_node
next_edge = None
for nxt, e_idx, p in adj[curr_node]:
if e_idx not in edge_visited:
next_edge = (nxt, e_idx, p)
break
if not next_edge:
break
nxt, e_idx, p = next_edge
edge_visited.add(e_idx)
chain_payloads.append(p)
curr_node = nxt
chains.append("".join(chain_payloads))
# 2. Check for remaining unvisited edges (indicates isolated cycles)
if len(edge_visited) < len(fragments):
raise ValueError("Invalid topology: Input contains isolated cycles or loops.")
return chains
Complexity Analysis
| Part | Operation | Time Complexity | Space Complexity |
|---|---|---|---|
| Part 1 | CSV Parsing | $\mathcal{O}(N)$ where $N$ is total character count | $\mathcal{O}(N)$ storage |
| Part 1 | select() Query | $\mathcal{O}(R \cdot C)$ for $R$ rows and $C$ projected cols | $\mathcal{O}(R \cdot C)$ output space |
| Part 2 (Base) | Directed Chain Assembly | $\mathcal{O}(F)$ where $F$ is fragment count | $\mathcal{O}(F)$ hash tables |
| Part 2 (Follow-up) | Undirected Multi-Chain Assembly | $\mathcal{O}(V + F)$ graph traversal | $\mathcal{O}(V + F)$ adjacency graph |