Recover Nested Pick-List From Truncated Stream
Medium · Coding & Algorithms · Software Engineer · Technical Screen
Problem Statement
An automated fulfillment line transmits pick-list payloads over a serial stream using a minimal nested text grammar built from only two constructs:
- Quoted item codes: text enclosed in double quotes (for example,
"mug"), containing printable ASCII characters with no double quotes or backslashes. - Bracketed tote groups: square brackets enclosing zero or more comma-separated entries (for example,
["mug", ["plate", "spoon"]]), where each entry is either an item code or another nested tote group.
Nothing else exists in the format—no numbers, booleans, null literals, or escape sequences.
Because the connection can drop after any character, the received string feed may end abruptly in the middle of transmission. Implement reconstruct_picklist to convert the received prefix into the Python str or nested list representing everything transmitted so far, without fabricating unstarted entries:
def reconstruct_picklist(feed: str) -> str | list:
Your parser must follow these exact recovery rules:
feedstarts with"or[and is guaranteed to be a non-empty prefix of some syntactically valid payload built solely from quoted item codes and bracketed groups.- When
feedis already completely closed, return its parsedstrorlistvalue directly. - The top-level payload may be a standalone quoted item code with no surrounding brackets at all; in that case, return a
str. - If the stream cuts off before an open item code receives its closing
", keep every character that arrived after the opening"(producing""if the cutoff happened immediately after"). - If the stream cuts off right after
,(and any following spaces) inside a bracketed group before the next entry begins, ignore the trailing separator rather than adding a blank item. - Every opened
[whose closing]never arrived must still appear in the returned structure, holding all entries started inside it prior to cutoff.
Examples
Example 1
Input: feed = '["mug", ["plate", "spoo'
Output: ['mug', ['plate', 'spoo']]
The outer group holds "mug" and an unclosed inner group. Inside the inner group, "plate" finished and the second item code was cut off after spoo, so 'spoo' is retained.
Example 2
Input: feed = '[["pen"], "pad", '
Output: [['pen'], 'pad']
The stream stopped right after a separating comma and space in the outer group before a third entry began, so only the first two entries appear.
Example 3
Input: feed = '[[ '
Output: [[]]
Two nested groups opened and only whitespace arrived inside the inner group before disconnection, yielding an empty inner list inside the outer list.
Example 4
Input: feed = '"crate-07"'
Output: 'crate-07'
The entire stream is a single finished top-level item code with no brackets, so that string is returned as-is.
Example 5
Input: feed = '"pal'
Output: 'pal'
A standalone top-level item code lost its closing quote, so all received characters after the opening quote are returned.
Constraints
1 <= len(feed) <= 10^5feed[0]is either"or[.- Every character inside a quoted item code is printable ASCII except
"and\. - Outside quoted item codes, only
[,],,,", and the space character' 'appear. - Bracketed groups nest to a depth of at most
500.
Step-by-step walkthrough
Understand the grammar and every cutoff state
Each stream carries a minimal subset of JSON constructed from only two building blocks: - Quoted item codes such as
"mug"(printable ASCII with no"or\escape characters inside). - Bracketed tote groups such as["mug", ["plate", "spoon"]], which may nest inside outer groups.Because the stream can terminate after any character,
feedis guaranteed to be a non-empty prefix of some valid complete payload, starting with"or[. Our goal is to return the exact Pythonstror nestedlistcorresponding to the characters received so far, without fabricating missing entries:Where the stream stops Example feed Expected output ------------------------------------ --------------------------- ---------------------------- 1. Mid-string (missing closing '"') '["mug", ["plate", "spoo' ['mug', ['plate', 'spoo']] 2. Immediately after opening '"' '["mug", "' ['mug', ''] 3. Immediately after '[' / spaces '[[ ' [[]] 4. After ',' and optional spaces '[["pen"], "pad", ' [['pen'], 'pad'] 5. After a complete top-level item '"crate-07"' 'crate-07'Watch out for one key detail:
[,], and,are allowed inside a quoted item code (such as"[x]"), where they are plain text characters rather than list delimiters.Why we scan left-to-right instead of calling a JSON parser
A library parser like
json.loads(feed)requires every quote and bracket to be closed, so it raises a syntax error on'["mug", ["plate", "spoo'.Could we patch the tail of
feed— appending"if a string is still open, stripping a trailing comma, and appending]for each unclosed[— before callingjson.loads? That works (and serves as a handy oracle in unit tests), but knowing whether a quote is open and counting only the[and]tokens outside quotes already requires walkingfeedfrom left to right. During that single left-to-right pass, we can assemble the nested lists directly.Key trick 1: attach each new list to its parent immediately
Maintain an explicit stack (a last-in, first-out list) named
open_binscontaining every bracketed group whose closing]has not arrived yet. The innermost active group is alwaysopen_bins[-1].When should a newly opened child list be placed inside its parent? If we waited until seeing
], any group left unclosed when the stream stopped would remain stranded on the stack. Instead, the moment[arrives, we createnew_bin = [], append it toopen_bins[-1]right away, and then pushnew_binontoopen_bins:Feed read so far: '["mug", [' outer_wrapper: [ * ] | v outer_bin: ['mug', * ] <-- open_bins[1] | v inner_bin: [ ] <-- open_bins[2] (top of stack: open_bins[-1])Because Python lists store object references rather than copies, items appended to
inner_binlater automatically appear insideouter_bin. If the stream ends before]arrives, every open group is already nested in its parent!Notice the dummy container
outer_wrapperat the base of the stack (open_bins = [outer_wrapper]). Becausefeedcan be a bare top-level string like'"pal'with zero brackets, starting withouter_wrapperlets top-level strings and top-level lists share the exact sameopen_bins[-1].append(...)logic, andouter_wrapper[0]cleanly unwraps the final result.Key trick 2: check `in_label` first and ignore commas
At every index, the parser sits in one of two modes tracked by
in_label:- Inside quotes (
in_label == True): Every character is ordinary text except", which finishes the item code. Checkingif in_label:first ensures characters like[or,inside"[x]"never open lists. Rather than concatenating characters one by one, we recordlabel_start = i + 1at the opening quote and slicefeed[label_start:i]once at the closing quote. - Outside quotes (
in_label == False):"enters quote mode (in_label = True,label_start = i + 1).[createsnew_bin = [], appends it toopen_bins[-1], and pushes it ontoopen_bins.]popsopen_binsbecause the innermost group is complete.,and' 'are ignored. Because entries are appended when"or[is processed — never on,— a cutoff right after,never creates a spurious empty element.
def scan_bytes(feed: str): outer_wrapper = [] open_bins = [outer_wrapper] in_label = False label_start = 0 for i, ch in enumerate(feed): if in_label: if ch == '"': completed_label = feed[label_start:i] open_bins[-1].append(completed_label) in_label = False elif ch == '"': in_label = True label_start = i + 1 elif ch == "[": new_bin = [] open_bins[-1].append(new_bin) open_bins.append(new_bin) elif ch == "]": open_bins.pop() return outer_wrapper, open_bins, in_label, label_start- Inside quotes (
Recover an interrupted string at end-of-stream
Once the loop finishes reading
feed, our state variables immediately reveal whether anything was cut off mid-token:- Unclosed groups: Already attached inside their parent lists, requiring zero cleanup.
- Unclosed item code (
in_label == True): No closing"arrived, so we slicefeed[label_start:]and append it toopen_bins[-1]. Even whenfeedends immediately after an opening quote (such as'["mug", "'),label_start == len(feed)andfeed[label_start:]evaluates to"", appending the expected empty string!
def finish_scan(feed: str, outer_wrapper: list, open_bins: list, in_label: bool, label_start: int): if in_label: partial_label = feed[label_start:] open_bins[-1].append(partial_label) return outer_wrapper[0]Trace Example 1 and Example 2 step by step
Let's walk through Example 1,
feed = '["mug", ["plate", "spoo', watchingin_label,label_start, andouter_wrapper[0]:Index Char(s) in_label Action outer_wrapper[0] ------ --------- --------- ---------------------------------------- ---------------------------- start - False open_bins = [outer_wrapper] (empty) 0 [ False create bin A, attach to outer, push A [] 1 " False->T label_start = 2 [] 2..4 mug True ordinary characters, keep scanning [] 5 " True ->F append feed[2:5] = 'mug' to bin A ['mug'] 6..7 , <space> False ignored ['mug'] 8 [ False create bin B, attach to A, push B ['mug', []] 9..15 "plate" F->T->F append 'plate' to bin B ['mug', ['plate']] 16..17 , <space> False ignored ['mug', ['plate']] 18 " False->T label_start = 19 ['mug', ['plate']] 19..22 spoo True ordinary characters, stream ends ['mug', ['plate']] EOF - True append feed[19:] = 'spoo' to bin B ['mug', ['plate', 'spoo']]Now check Example 2,
feed = '[["pen"], "pad", ': -[opens the outer group,[opens the inner group,"pen"appends'pen', and]pops back to the outer group ([['pen']]). -, "pad"appends'pad'to the outer group ([['pen'], 'pad']). - The trailing,is ignored andin_labelisFalseat EOF, soouter_wrapper[0]returns[['pen'], 'pad'].Complete solution
Putting both phases together gives the complete
O(n)parser:from typing import Any, Dict, List, Optional, Set, Tuple def reconstruct_picklist(feed: str) -> str | list: # Dummy wrapper list that captures the single top-level value at index 0, # unifying feeds that start with a label ('"abc') and feeds that start with '['. outer_wrapper: List[Any] = [] # Stack of bins whose closing ']' has not arrived yet (innermost bin is last). # Shape: [outer_wrapper, outer_bin, inner_bin, ...] open_bins: List[List[Any]] = [outer_wrapper] # Separate state for whether the scanner is currently inside "...". in_label = False label_start = 0 # index of the first character after the opening '"' # Phase 1: Scan the received bytes left to right in one pass. for i, ch in enumerate(feed): if in_label: # Inside quotes, ONLY '"' has special meaning; '[', ']', and ',' are plain text. if ch == '"': completed_label = feed[label_start:i] open_bins[-1].append(completed_label) in_label = False elif ch == '"': # Begin recording a new label starting right after this opening quote. in_label = True label_start = i + 1 elif ch == "[": # Attach new_bin to its parent immediately so Python list references keep it # in the final output even if the feed cuts off before its matching ']'. new_bin: List[Any] = [] open_bins[-1].append(new_bin) open_bins.append(new_bin) elif ch == "]": # Close the innermost open bin; valid-prefix guarantee ensures outer_wrapper stays. open_bins.pop() # Outside quotes, ',' and ' ' carry no data; ignoring ',' means a trailing comma # right before cutoff never creates a phantom empty entry. # Phase 2: Recover any label whose closing '"' never arrived before the stream ended. if in_label: # If feed ended right after '"', label_start == len(feed), giving "" as required. partial_label = feed[label_start:] open_bins[-1].append(partial_label) return outer_wrapper[0]✅ Submit now — all tests should pass.
Intuition & how it works
Imagine organizing nested shipping totes on a packing bench while reading instructions off a ticker tape that can tear off mid-word. Whenever the tape says "open a sub-tote," you immediately set that empty sub-tote inside whichever tote you are currently filling, rather than setting it aside until it is full. That way, if the tape tears abruptly, every open tote — no matter how deeply nested — is already sitting inside its parent tote, and the only unfinished detail is dropping in whatever partial item tag you were reading when the tape ended.
Why do off-the-shelf approaches fall short? Passing a truncated string directly to json.loads raises a syntax error whenever a closing " or ] is missing. You could try repairing the end of the text first (closing an unclosed quote, removing any trailing comma, and adding missing ] brackets), and while that works, counting unclosed brackets without getting tricked by [ or ] characters inside quoted strings already requires scanning the characters from left to right. Building the Python result directly during that single pass is cleaner and avoids scanning twice.
Our parser works as a two-mode state machine (a loop that tracks its current mode — here in_label = True or False — to decide what each character means) paired with an explicit stack (a last-in, first-out list open_bins whose last element open_bins[-1] is always the innermost open group) and a sentinel (outer_wrapper = [], a dummy outer list so a standalone top-level string and a top-level list share the exact same append logic). Here is how it walks '["mug", ["plate", "spoo':
1. '[' -> create outer list [], place inside outer_wrapper, push onto open_bins
2. '"mug"' -> slice 'mug', append to outer list -> ['mug']
3. ', ' -> outside quotes, commas and spaces are ignored
4. '[' -> create inner list [], place inside outer list, push -> ['mug', []]
5. '"plate"' -> slice 'plate', append to inner list -> ['mug', ['plate']]
6. ', "spoo' -> sets in_label=True at index 19; stream ends -> append feed[19:]='spoo'
Result: outer_wrapper[0] == ['mug', ['plate', 'spoo']]
Complexity
Let n be len(feed) and d be the maximum bracket nesting depth (d <= 500).
- Time:
O(n). We inspect each character offeedonce withO(1)list push, pop, or integer updates per character, and copy each string character at most once when slicingfeed[label_start:i]orfeed[label_start:]. - Space:
O(n)overall (orO(d)auxiliary stack space beyond the returned structure). The output holds up toO(n)characters and nested list elements, whileopen_binsstores at mostd + 1list references at once.
Edge cases
- Standalone top-level string with no brackets:
'"crate-07"'returns'crate-07','"pal'returns'pal', and a lone'"'returns''becauseouter_wrapper[0]unwraps the single top-level entry. - Cutoff right after an opening quote inside a list:
'["mug", "'leavesin_label = Truewithlabel_start == len(feed), sofeed[label_start:]appends''to produce['mug', '']. - Cutoff right after
[(with or without spaces):'['returns[]and'[[ 'returns[[]]because each new list is attached to its parent immediately upon seeing[. - Cutoff after a trailing comma and spaces:
'[["pen"], "pad", 'returns[['pen'], 'pad']because commas never push a placeholder entry. - Delimiters inside quoted strings:
'["[x]", ",", "y]'returns['[x]', ',', 'y]']becausein_labelis checked before[,], or,. - Deep nesting (
500levels): Maintainingopen_binsexplicitly avoids Python's call-stack recursion limit (1000frames by default).
Common mistakes
- Checking
[or]beforein_label: If bracket branches run whilein_labelisTrue, an item code like"[x]"corruptsopen_bins. - Appending entries when
,is read: Flushing a buffer on,causes trailing-comma cutoffs like'[["pen"], "pad", 'to append a bogus empty item. - Attaching child lists only when
]arrives: Any group whose closing]was lost stays stranded onopen_binsunless you write an extra post-processing loop to fold unclosed lists into their parents. - Building strings via
cur += chin a loop: Repeated concatenation can degrade towardO(n²)on a single10^5-character string; slicingfeed[label_start:i]once is guaranteed linear. - Returning
outer_wrapperinstead ofouter_wrapper[0]: Wraps standalone strings like'"crate-07"'in an unwanted list['crate-07'].
Alternative approaches
- Repair the suffix and invoke
json.loads: Count quotes to see whetherfeedended inside a string and count[minus]outside quotes; append"(or strip trailing spaces and,), append"]" * open_count, and pass the patched string tojson.loads. StillO(n)time and great as a test cross-check, though it traverses the input twice. - Recursive descent (
parse_entry(idx)calling itself on[): Matches the nested grammar cleanly, but requires truncation checks at every step and risks approaching Python's recursion limit near depth500.
Follow-up questions
- How could you add another literal form—such as single-quoted integer IDs—while keeping the single-pass loop structure intact? Replace the boolean
in_labelwith a small state variabletoken_kind(None,"str", or"int") driven by a delimiter table mapping"to('"', str)and'to("'", int). The[,],,, and space cases stay unchanged. You would only need to agree on truncation semantics for numbers: if'42'cuts off at'4, you either convert the partial digits (4) or discard unclosed integer tokens when acting on half-transmitted IDs would be unsafe. - Suppose the transport layer periodically injects a reserved keep-alive control byte anywhere in the stream, including inside a quoted string; how would you filter it out? As long as that control byte (say
\x00) never legitimately appears in item codes, putif ch == KEEP_ALIVE: continueat the very top of the loop so it is skipped both inside and outside quotes. Because keep-alive bytes inside a string break contiguous slicing offeed, replacelabel_startwith a character bufferbuf: List[str] = [], append each non-control character whilein_labelisTrue, and"".join(buf)when the quote closes or the stream ends. If the keep-alive byte could also occur in real text, the wire format would have to introduce escaping to distinguish control bytes from payload bytes. - If new character chunks arrive incrementally over a live socket, how would you turn this function into an incremental parser that avoids re-reading earlier chunks? Encapsulate
outer_wrapper,open_bins,in_label, andbuf: List[str]inside aStreamingPicklistParserclass whosefeed_chunk(chunk: str)method runs the same character loop over only the new chunk, keeping cumulative workO(total_bytes). When a caller requestssnapshot()whilein_labelisTrue, temporarily append"".join(buf)toopen_bins[-1](or update an in-place slot atopen_bins[-1][-1]until the closing"arrives) so repeated snapshots never duplicate partial strings. - Which minimal suite of test inputs is sufficient to exercise every possible cutoff state in the grammar? Eight tiny inputs cover every state transition and cutoff boundary:
'["mug", ["spoo'(mid-string inside nested unclosed groups),'["mug", "'(immediately after an opening quote),'['(immediately after[),'["mug", '(after comma + space),'[["mug"]'(immediately after an inner]),'"pal'(standalone string cut mid-word),'"crate-07"'(standalone string complete), and'["[x]", ","]'(fully closed list containing brackets and commas inside quotes).
Follow-up questions
- How could you add another literal form—such as single-quoted integer IDs—while keeping the single-pass loop structure intact?
- Suppose the transport layer periodically injects a reserved keep-alive control byte anywhere in the stream, including inside a quoted string; how would you filter it out?
- If new character chunks arrive incrementally over a live socket, how would you turn this function into an incremental parser that avoids re-reading earlier chunks?
- Which minimal suite of test inputs is sufficient to exercise every possible cutoff state in the grammar?
Similar questions
- Streaming Partial JSON Parser for Strings and Arrays
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance
- Increment Fixed-Size Digit Array by One