Multi-Tab Split-Pane Terminal State
Medium · Coding & Algorithms · Software Engineer · Technical Screen
Problem Statement
Build an in-memory state model for a terminal application that manages multiple tabs and nested two-way split panes, along with exact snapshot serialization and restoration.
Layout & Addressing Model
- A
Terminalstarts with zero tabs (tabs = []) and a single terminal-wide integer counternext_panel_id = 0. Every newly created panel across all tabs consumesnext_panel_idand increments it by1. - Each
Tabowns a binary tree ofPanelnodes rooted atroot. - Each
Panelhas an integerpanel_idand is either:- a leaf pane (unsplit, zero children), or
- a split container with a
splitdirection ("horizontal"or"vertical") and two ordered children[first_child, second_child].
- Inside a tab, a panel is addressed by a
0-based indexpath: List[int]starting atroot:[]selectsroot,[0]selectsroot's first child,[1, 0]selects the first child ofroot's second child, and so on.
Operations
Implement terminal_operations(operations, arguments), which starts from an empty Terminal, executes operations[k] with arguments[k] in order, and returns a list of results (one per command):
"new_tab"(arguments[k] = []): Allocates a fresh leaf root panel usingnext_panel_id, appends a new tab, and returns the new tab's0-based index (int)."split_panel"(arguments[k] = [tab_index, path, direction]): Splits the leaf panel at(tab_index, path)into two fresh leaf child panels with IDs[next_panel_id, next_panel_id + 1](advancingnext_panel_idby2) and returns[first_id, second_id]. Iftab_indexis out of bounds,directionis neither"horizontal"nor"vertical", any index inpathis negative or out of range, or the target panel is already split, leave both the layout andnext_panel_idunchanged and returnNone."serialize"(arguments[k] = []): Returns an independent nested dictionary snapshot of the entire terminal:- Top level:
{"tabs": [{"root": <panel_dict>}, ...], "next_panel_id": <int>} - Leaf panel:
{"panel_id": <int>}(omitting"split"and"children") - Split panel:
{"panel_id": <int>, "split": <str>, "children": [<first_dict>, <second_dict>]} - Later mutations must never alter an earlier serialized snapshot.
- Top level:
"deserialize"(arguments[k] = [state]): Replaces the active terminal (its tabs andnext_panel_id) with an independentTerminalreconstructed fromstate(so later mutations never modifystate), and returnsTrue.
def terminal_operations(operations: List[str], arguments: List[List]) -> List:
Examples
Example 1
Input:
operations = [
"new_tab", "new_tab",
"split_panel", "split_panel",
"serialize", "deserialize", "serialize"
]
arguments = [
[], [],
[0, [], "vertical"], [0, [1], "horizontal"],
[], [S], []
]
where S = {
"tabs": [
{
"root": {
"panel_id": 0,
"split": "vertical",
"children": [
{"panel_id": 2},
{
"panel_id": 3,
"split": "horizontal",
"children": [{"panel_id": 4}, {"panel_id": 5}],
},
],
}
},
{"root": {"panel_id": 1}},
],
"next_panel_id": 6,
}
Output: [0, 1, [2, 3], [4, 5], S, True, S]
Explanation: Opening two tabs assigns root IDs 0 and 1. Splitting Tab 0's root ([]) vertically creates children [2, 3], and splitting its second child ([1], panel 3) horizontally creates children [4, 5], advancing next_panel_id to 6. Serializing, deserializing S, and serializing again reproduces S identically.
Example 2
Input:
operations = ["new_tab", "split_panel", "split_panel", "split_panel", "split_panel"]
arguments = [[], [0, [], "diagonal"], [0, [], "horizontal"], [0, [], "vertical"], [0, [0], "vertical"]]
Output: [0, None, [1, 2], None, [3, 4]]
Explanation: "diagonal" is rejected without consuming IDs, so splitting Tab 0's root horizontally next receives [1, 2]. Trying to split Tab 0's root a second time returns None because it is no longer a leaf, leaving IDs [3, 4] for splitting child [0].
Constraints
1 <= len(operations) == len(arguments) <= 200- Every command in
operationsis"new_tab","split_panel","serialize", or"deserialize" - Every
"deserialize"inputstateis a valid serialized terminal dictionary
Step-by-step walkthrough
Understand the layout tree and the judge contract
When you split panes in a terminal app, each split divides one rectangular pane into two child panes inside that same space, and either child can be split again. That nested layout maps directly to a binary tree:
Screen view of Tab 0: Tree representation of Tab 0: +-----------------------+ Panel 0 | Panel 2 | (split: "vertical") | path [0] | / \ +-----------+-----------+ Panel 2 Panel 3 | Panel 4 | Panel 5 | (leaf) (split: "horizontal") | path[1,0] | path[1,1] | / \ +-----------+-----------+ Panel 4 Panel 5 (leaf) (leaf)Notice how leaves (nodes with no children) are the actual visible panes on screen, while internal nodes record the split direction (
"horizontal"or"vertical") and hold[first_child, second_child]. A panel inside a tab is addressed by apathof child indices starting from the tab's root:[]is the root itself,[1]is its second child, and[1, 0]is the first child of that second child.The automated judge calls
terminal_operations(operations, arguments)and expects one result per operation: -new_tab(): Appends a new tab containing one fresh root panel (using the next global panel ID) and returns the new tab's0-based index. -split_panel(tab_index, path, direction): Splits the leaf panel at(tab_index, path)into two new child panels with the next two global panel IDs and returns[first_id, second_id]. Iftab_indexis invalid,directionis not"horizontal"or"vertical",pathleaves the tree, or the target panel is already split, returnNoneand change nothing (not even the ID counter). -serialize(): Returns{"tabs": [{"root": ...}, ...], "next_panel_id": n}, where a leaf serializes as{"panel_id": id}and a split node adds"split"and"children". -deserialize(state): Replaces the terminal with a freshTerminalreconstructed fromstateand returnsTrue.Design `Panel` and `Tab` with safe path lookup
Splitting responsibilities across three focused classes keeps every method tiny and easy to reason about: -
Panel: One tree node (panel_id,split,children). -Tab: Wraps oneroot: Paneland walks apathto locate any nested panel. -Terminal: Ownstabs: List[Tab]and the single sharednext_panel_idcounter.Inside
Tab.find_panel(path), pay close attention tochild_index < 0: in Python,panel.children[-1]is legal syntax that silently returns the last child instead of failing! Checkingchild_index < 0 or child_index >= len(current.children)rejects both negative indices and indices past the end (including any attempt to step below a leaf, since a leaf haslen(current.children) == 0).class Panel: """One node in a tab's binary split tree: either a visible leaf pane or a 2-way split.""" def __init__(self, panel_id: int): self.panel_id = panel_id # split is None for a leaf pane, or "horizontal" / "vertical" once split. self.split: Optional[str] = None # children is empty [] for a leaf pane, or [first_child, second_child] once split. self.children: List["Panel"] = [] class Tab: """One terminal tab owning the root Panel of its layout tree.""" def __init__(self, root: Panel): self.root = root def find_panel(self, path: List[int]) -> Optional[Panel]: """Walk child indices starting at `root`; return None if any step is out of range.""" current = self.root for child_index in path: if child_index < 0 or child_index >= len(current.children): return None current = current.children[child_index] return currentImplement `new_tab` and atomic `split_panel` on `Terminal`
In Example 1, opening Tab 0 and Tab 1 assigns root panel IDs
0and1, and splitting Tab 0's root next allocates IDs2and3. That confirmsnext_panel_idbelongs onTerminal, shared across all tabs.When implementing
split_panel, two invariants prevent subtle state corruption: 1. Only leaves can be split (target_panel.split is None): Splitting an already-split node would overwrite its existing children. 2. Validate everything before calling_allocate_panel(): If we allocated new panel IDs first and then discovereddirection == "diagonal"orpathwas invalid,next_panel_idwould have advanced on a failed call, shifting every subsequent panel ID!VALID_DIRECTIONS = ("horizontal", "vertical") class Terminal: def __init__(self): self.tabs: List[Tab] = [] self.next_panel_id = 0 def _allocate_panel(self) -> Panel: panel = Panel(self.next_panel_id) self.next_panel_id += 1 return panel def new_tab(self) -> int: root_panel = self._allocate_panel() self.tabs.append(Tab(root_panel)) return len(self.tabs) - 1 def split_panel( self, tab_index: int, path: List[int], direction: str ) -> Optional[List[int]]: if tab_index < 0 or tab_index >= len(self.tabs): return None if direction not in VALID_DIRECTIONS: return None target_panel = self.tabs[tab_index].find_panel(path) if target_panel is None or target_panel.split is not None: return None first_child = self._allocate_panel() second_child = self._allocate_panel() target_panel.split = direction target_panel.children = [first_child, second_child] return [first_child.panel_id, second_child.panel_id]Serialize and deserialize recursively without shared references
Look closely at the two dictionary shapes in the serialized tree:
Leaf node: {"panel_id": 2} Split node: {"panel_id": 3, "split": "horizontal", "children": [{"panel_id": 4}, {"panel_id": 5}]}Notice that a leaf omits
"split"and"children"rather than writing"split": None. Because a tree is naturally recursive — every child of aPanelis itself aPanel— bothto_dict()andfrom_dict()are clean recursive walks: -to_dict()creates brand-new dictionaries and lists on every call, so a caller holding an oldserialize()snapshot never sees it mutate when later splits happen. -from_dict()creates brand-newPanelobjects on every call, so mutating a restoredTerminalnever modifies thestatedictionary passed intodeserialize(state). -Terminal.serialize()andTerminal.deserialize()also save and restorenext_panel_iddirectly so future tabs and splits keep issuing fresh, non-colliding IDs (even ifnext_panel_idis higher thanmax_id + 1, as happens once panels can be closed).class Panel: # ... __init__ ... def to_dict(self) -> Dict[str, Any]: if self.split is None: return {"panel_id": self.panel_id} serialized_children: List[Dict[str, Any]] = [] for child in self.children: serialized_children.append(child.to_dict()) return { "panel_id": self.panel_id, "split": self.split, "children": serialized_children, } @staticmethod def from_dict(data: Dict[str, Any]) -> "Panel": panel = Panel(data["panel_id"]) if "split" in data: panel.split = data["split"] for child_data in data["children"]: panel.children.append(Panel.from_dict(child_data)) return panelclass Terminal: # ... __init__, _allocate_panel, new_tab, split_panel ... def serialize(self) -> Dict[str, Any]: serialized_tabs: List[Dict[str, Any]] = [] for tab in self.tabs: serialized_tabs.append({"root": tab.root.to_dict()}) return { "tabs": serialized_tabs, "next_panel_id": self.next_panel_id, } @staticmethod def deserialize(state: Dict[str, Any]) -> "Terminal": terminal = Terminal() for tab_data in state["tabs"]: root_panel = Panel.from_dict(tab_data["root"]) terminal.tabs.append(Tab(root_panel)) terminal.next_panel_id = state["next_panel_id"] return terminalWire up the command dispatcher and round-trip verification
terminal_operationsloops over(op, args)pairs, dispatches each method on the currentterminal, replacesterminal = Terminal.deserialize(args[0])on"deserialize", and collects every return value.We also include a self-contained
if __name__ == "__main__":check that creates multiple tabs, performs nested splits, serializes, deserializes into a freshTerminalinstance, and asserts exact structural equality:def terminal_operations(operations: List[str], arguments: List[List]) -> List: terminal = Terminal() results: List[Any] = [] for op, args in zip(operations, arguments): if op == "new_tab": results.append(terminal.new_tab()) elif op == "split_panel": tab_index, path, direction = args results.append(terminal.split_panel(tab_index, path, direction)) elif op == "serialize": results.append(terminal.serialize()) elif op == "deserialize": terminal = Terminal.deserialize(args[0]) results.append(True) return resultsTrace Example 1 step by step
1. new_tab() -> returns 0 Tab 0: 0(leaf) | next_panel_id = 1 2. new_tab() -> returns 1 Tab 1: 1(leaf) | next_panel_id = 2 3. split_panel(0, [], "vertical") -> returns [2, 3] Tab 0: 0(V) -> [2(leaf), 3(leaf)] | next_panel_id = 4 4. split_panel(0, [1], "horizontal") -> returns [4, 5] Tab 0: 0(V) -> [2(leaf), 3(H) -> [4(leaf), 5(leaf)]] | next_panel_id = 6 5. serialize() -> returns dict S (with next_panel_id: 6) 6. deserialize(S) -> rebuilds fresh Terminal, returns True 7. serialize() -> returns dict identical to SComplete solution
from typing import Any, Dict, List, Optional, Set, Tuple VALID_DIRECTIONS = ("horizontal", "vertical") class Panel: """One node in a tab's binary split tree: either a visible leaf pane or a 2-way split.""" def __init__(self, panel_id: int): self.panel_id = panel_id # split is None for a leaf pane, or "horizontal" / "vertical" once split. self.split: Optional[str] = None # children is empty [] for a leaf pane, or [first_child, second_child] once split. self.children: List["Panel"] = [] def to_dict(self) -> Dict[str, Any]: # Leaf format omits "split" and "children": {"panel_id": 2} if self.split is None: return {"panel_id": self.panel_id} # Split format recursively serializes children into fresh dicts/lists so callers # cannot accidentally mutate live Terminal state through a serialized snapshot. serialized_children: List[Dict[str, Any]] = [] for child in self.children: serialized_children.append(child.to_dict()) return { "panel_id": self.panel_id, "split": self.split, "children": serialized_children, } @staticmethod def from_dict(data: Dict[str, Any]) -> "Panel": # Rebuild fresh Panel instances recursively so mutating the restored Terminal later # never modifies the input `data` dictionary. panel = Panel(data["panel_id"]) if "split" in data: panel.split = data["split"] for child_data in data["children"]: panel.children.append(Panel.from_dict(child_data)) return panel class Tab: """One terminal tab owning the root Panel of its layout tree.""" def __init__(self, root: Panel): self.root = root def find_panel(self, path: List[int]) -> Optional[Panel]: """Walk child indices starting at `root`; return None if any step is out of range.""" current = self.root for child_index in path: # Check child_index < 0 explicitly because Python's list[-1] would otherwise # treat a negative index as the last child instead of rejecting an invalid path! if child_index < 0 or child_index >= len(current.children): return None current = current.children[child_index] return current class Terminal: """Multi-tab terminal state with globally unique panel IDs and snapshot support.""" def __init__(self): # tabs: ordered list of Tab objects (indexed 0, 1, ...) self.tabs: List[Tab] = [] # next_panel_id: monotonic counter shared across ALL tabs so IDs never collide self.next_panel_id = 0 def _allocate_panel(self) -> Panel: panel = Panel(self.next_panel_id) self.next_panel_id += 1 return panel def new_tab(self) -> int: root_panel = self._allocate_panel() self.tabs.append(Tab(root_panel)) return len(self.tabs) - 1 def split_panel( self, tab_index: int, path: List[int], direction: str ) -> Optional[List[int]]: """Split the leaf panel at `(tab_index, path)` into two child panels, or return None.""" # Validate tab, direction, path, and leaf status BEFORE allocating panel IDs # so failed operations leave both the tree and `next_panel_id` completely unchanged. if tab_index < 0 or tab_index >= len(self.tabs): return None if direction not in VALID_DIRECTIONS: return None target_panel = self.tabs[tab_index].find_panel(path) if target_panel is None or target_panel.split is not None: return None first_child = self._allocate_panel() second_child = self._allocate_panel() target_panel.split = direction target_panel.children = [first_child, second_child] return [first_child.panel_id, second_child.panel_id] def serialize(self) -> Dict[str, Any]: serialized_tabs: List[Dict[str, Any]] = [] for tab in self.tabs: serialized_tabs.append({"root": tab.root.to_dict()}) return { "tabs": serialized_tabs, "next_panel_id": self.next_panel_id, } @staticmethod def deserialize(state: Dict[str, Any]) -> "Terminal": terminal = Terminal() for tab_data in state["tabs"]: root_panel = Panel.from_dict(tab_data["root"]) terminal.tabs.append(Tab(root_panel)) terminal.next_panel_id = state["next_panel_id"] return terminal def terminal_operations(operations: List[str], arguments: List[List]) -> List: # Replay each command against the active Terminal instance and collect return values. terminal = Terminal() results: List[Any] = [] for op, args in zip(operations, arguments): if op == "new_tab": results.append(terminal.new_tab()) elif op == "split_panel": tab_index, path, direction = args results.append(terminal.split_panel(tab_index, path, direction)) elif op == "serialize": results.append(terminal.serialize()) elif op == "deserialize": terminal = Terminal.deserialize(args[0]) results.append(True) return results if __name__ == "__main__": # Self-test: create tabs, perform nested splits, serialize, deserialize, and verify match. original = Terminal() original.new_tab() original.new_tab() original.split_panel(0, [], "vertical") original.split_panel(0, [1], "horizontal") snapshot = original.serialize() restored = Terminal.deserialize(snapshot) assert restored is not original assert restored.serialize() == snapshot✅ Submit now — all tests should pass.
Intuition & how it works
Think of splitting panes in a modern terminal app (like Warp, iTerm2, or tmux) like cutting a sheet of paper inside a picture frame: a brand-new tab starts as one undivided sheet — a leaf node (a tree node with no children, representing an actual visible terminal pane). Whenever you split a pane horizontally or vertically, that rectangle turns into an invisible layout container — an internal node — that remembers the split direction and holds two smaller child panes (children[0] and children[1]), either of which can later be split again!
Why do simpler data structures fall short? Storing a tab's panes as a flat list loses the nested parent-child grouping needed to know which panes sit side by side versus stacked inside one half of an earlier split. Likewise, storing raw caller dictionaries directly without constructing separate Panel objects leads to aliasing bugs (unintended shared references where splitting a pane later silently mutates an earlier snapshot dictionary returned by serialization — converting live in-memory objects into plain nested data — or passed into deserialization — rebuilding live objects from plain data).
Here is how Tab 0 evolves across Example 1, using child-index paths ([] = root, [1] = second child):
1. new_tab(), new_tab() -> Tab 0 root: Panel 0 (leaf), Tab 1 root: Panel 1 (leaf)
2. split_panel(0, [], "vertical") -> Panel 0 (vertical)
+-- [0] Panel 2 (leaf)
+-- [1] Panel 3 (leaf)
3. split_panel(0, [1], "horizontal") -> Panel 0 (vertical)
+-- [0] Panel 2 (leaf)
+-- [1] Panel 3 (horizontal)
+-- [1,0] Panel 4 (leaf)
+-- [1,1] Panel 5 (leaf)
Complexity
Let P be the total number of Panel nodes across all tabs, and let d = len(path) be the depth of a target panel in its tab's tree.
new_tab():- Time:
O(1)amortized, because we allocate onePanel, incrementnext_panel_id, and append oneTabtoself.tabs. - Space:
O(1)for the single newTaband rootPanel.
- Time:
split_panel(tab_index, path, direction):- Time:
O(d), becausefind_panelsteps through at mostdchild pointers from the tab's root before attaching two newPanelchildren inO(1)time. - Space:
O(1)for the two newly created childPanelinstances.
- Time:
serialize()anddeserialize(state):- Time:
O(P), because the recursive tree walk visits each of thePpanel nodes exactly once and performsO(1)dictionary/object work per node. - Space:
O(P), for thePnewly constructed dictionaries (orPanelobjects) plusO(H)call-stack frames whereH <= Pis the maximum split depth.
- Time:
Edge cases
- Empty terminal (zero tabs):
serialize()cleanly returns{"tabs": [], "next_panel_id": 0}, and anysplit_panelcall fails thetab_indexbounds check and returnsNone. - Splitting a tab's root (
path = []): The loop infind_panel([])runs zero iterations and immediately returnsself.root. - Out-of-bounds or negative paths (
[2],[0, 0]below a leaf, or[-1]): Rejected bychild_index < 0 or child_index >= len(current.children), returningNonewith zero side effects. - Splitting an already-split panel: Rejected by
target_panel.split is not Noneso existing subtrees are never overwritten. - Failed split preserves
next_panel_id: Because all validation happens before_allocate_panel(), invalid calls never leave gaps in panel IDs. - Continuing after
deserialize:deserializereplaces all prior tabs and restoresstate["next_panel_id"], so subsequentnew_tabandsplit_panelcalls seamlessly continue from the saved counter. - Snapshot isolation: Both
to_dict()andfrom_dict()allocate fresh dicts, lists, andPanelobjects, so later splits never mutate an earlier serialized dict or the caller's input dict.
Common mistakes
- Resetting panel IDs per tab (
0, 1, 2in every tab): Example 1 assignspanel_id = 0to Tab 0's root,panel_id = 1to Tab 1's root, and[2, 3]to Tab 0's first split, confirmingnext_panel_idis global across the wholeTerminal. - Including
"split": None, "children": []on leaf dicts: The expected leaf representation is strictly{"panel_id": id}; extra keys fail structural equality checks. - Forgetting
child_index < 0in Python: Without an explicit< 0check,current.children[-1]succeeds on any split node and splits its second child instead of returningNone! - Allocating new panel IDs before validation: Calling
_allocate_panel()at the top ofsplit_panelburns two IDs whenever the path or direction turns out to be invalid. - Recomputing
next_panel_idasmax_id + 1ondeserialize: Ifstatehasnext_panel_id = 8while its highest existing panel ID is3(for example after panels were closed), recomputing3 + 1 = 4violates the saved counter and breaks subsequent IDs.
Alternative approaches
- Direct nested-dict manipulation: Keep the terminal's internal state in the exact serialized dictionary format and use
copy.deepcopyonserializeanddeserialize(as the test suite's reference oracle does). Concise for small scripts, but string-keyed dicts give up clear class invariants, type hints, and encapsulation as features like focus, scrollback buffers, or resize ratios are added. - Flat node table (
panel_id -> PanelRecord): Store all panels in a flat hash map keyed bypanel_idwithparent_idandchild_ids. Makes lookup bypanel_idO(1), thoughserialize()still has to recursively assemble the nested tree output.
Follow-up questions
- How would you add a
close_panel(tab_index, path)operation while keeping the binary split tree minimal? Only a leaf panel can be closed directly. When a leaf closes, its parent split node is left with just one surviving child, so we collapse that redundant split by replacing the parent node with the surviving sibling's entire subtree (either by walkingpath[:-1]to reach the parent and updating the grandparent's child slot, or by storing aparentpointer on eachPanel). If the closed leaf was the tab'srootitself, we remove the tab fromself.tabs— while keepingself.next_panel_iduntouched so closed IDs are never reused! - What validation checks would you add to
deserializebefore loading snapshots from untrusted files on disk? Parse JSON into raw Python primitives (json.loads), check a"schema_version"field for forward compatibility, and validate the entire tree before replacing the live terminal: verify every node has an integer"panel_id"with no duplicates, every split node has"split"in("horizontal", "vertical")and"children"of length2, every leaf has neither key, andnext_panel_idis strictly greater than every"panel_id"seen. If any check fails, raise aValueError(or returnFalse) while leaving the activeTerminaluntouched. - How would you extend the model to store adjustable split ratios and support
O(1)lookup bypanel_id? Add asplit_ratio: float = 0.5field (clamped to e.g.[0.1, 0.9]) on internalPanelnodes representing the fraction of width or height given tochildren[0], and include"ratio"into_dict()/from_dict(). ForO(1)panel lookup by ID (useful when a shell process exits and reports only itspanel_id), maintain an indexself.panels_by_id: Dict[int, Panel]onTerminal, updated in_allocate_panel()and rebuilt duringdeserialize().
Follow-up questions
- How would you add a `close_panel(tab_index, path)` operation while keeping the binary split tree minimal?
- What validation checks would you add to `deserialize` before loading snapshots from untrusted files on disk?
- How would you extend the model to store adjustable split ratios and support `O(1)` lookup by `panel_id`?
Similar questions
- 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
- Increment Digit Array