Group Deletion Stack and Boundary Path Collection
Stacks & QueuesModel answerLast updated
Remove consecutive identical-character groups from a string and collect a binary tree's boundary nodes in a specific mirror order.
You are given two independent algorithmic tasks to solve:
Task 1: Consecutive Group Removal
Given a string s containing only lowercase letters, repeatedly remove any contiguous substring of two or more identical characters. When a removal causes previously non-adjacent characters to become neighbors, they may form a new removable group. Continue until no more removals are possible.
For example, "abbbaaccz":
- Remove
"bbb"→"aaaccz" - Remove
"aaa"→"ccz" - Remove
"cc"→"z"
Return the final string after all possible removals.
Requirements:
- Achieve O(n) time and O(n) space complexity
- Explain why your algorithm terminates and produces the correct result
- Extension 1: Generalize to remove groups of length ≥ k (where k ≥ 2)
- Extension 2: Support streaming input where characters arrive one at a time
Task 2: Boundary Node Collection
Given the root of a binary tree, construct a list of node values following this specific traversal order:
- Collect all nodes along the left boundary path (from
root.left, always preferring the left child, falling back to the right child if no left child exists, until reaching a leaf) and list them in reverse order (deepest to shallowest) - Add the root value
- Collect all nodes along the right boundary path (from
root.right, always preferring the right child, falling back to the left child if no right child exists, until reaching a leaf) in top-down order
Each node should appear exactly once in the output.
Requirements:
- Achieve O(n) time and O(h) space, where h is the tree height
- Handle cases where left or right subtrees are missing
Hints
Hint 1
For group removal, consider maintaining a stack of (character, count) pairs—how can you detect when a group becomes complete and should be removed?
Hint 2
The boundary paths are simple root-to-leaf walks, not full tree traversals. Each boundary is a single path following a greedy rule.
Hint 3
For streaming group removal, the stack itself represents your current state. Can you always emit characters early, or might future input cause earlier characters to be removed?
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Solution
Both problems reward careful invariant maintenance and single-pass algorithms.
Task 1: Consecutive Group Removal
Algorithm Design
The core challenge is handling cascading merges. When we remove "bbb" from "abbbaaccz", the 'a' characters on either side merge into a new group "aaa" that must also be removed.
Approach: Maintain a stack of run-length encoded segments as (character, count) pairs. Process the string left-to-right:
- When character
carrives, check if the top of the stack has the same character- If yes, increment its count
- If no, check whether the top run is complete and deletable (count ≥ k)
- When a run becomes deletable (count ≥ k and a different character arrives), pop it
- After popping, the new top may have character
c—if so, increment its count (this is the merge) - If no merge happens, push a new run
(c, 1)
At the end of input, check if the final run on top is deletable.
Why It's Correct:
We maintain the invariant that all runs below the top have count < k. Each run is removed exactly when it becomes complete (followed by a different character) and has length ≥ k. This simulates left-to-right deletion order. When two runs merge after a deletion, we handle it immediately by combining counts.
Why It Terminates:
Each deletion removes at least k ≥ 2 characters from a string of finite length n, so at most ⌊n/k⌋ deletions can occur. Our single-pass algorithm performs exactly this logical sequence of operations.
Complexity:
- Time: O(n) — Each character is pushed once and popped at most once
- Space: O(n) — Worst case when no deletions occur (e.g.,
"abcdefg")
Extensions
General k: The algorithm already handles arbitrary k ≥ 2 via the comparison count >= k.
Streaming: The stack is stateful. Method feed(c) processes one character; method result() applies end-of-input logic. We cannot emit any prefix early because future input might erase earlier characters (e.g., "abcd" followed by "dcba" can erase everything).
Implementation
class StreamingCleaner:
def __init__(self, k: int = 2):
self.k = k
self.stack = [] # [(char, count), ...]
def feed(self, c: str) -> None:
# Check if top run has same character
if self.stack and self.stack[-1][0] == c:
self.stack[-1] = (c, self.stack[-1][1] + 1)
return
# Top run is complete; check if deletable
if self.stack and self.stack[-1][1] >= self.k:
self.stack.pop()
# After deletion, check for merge
if self.stack and self.stack[-1][0] == c:
self.stack[-1] = (c, self.stack[-1][1] + 1)
return
# Push new run
self.stack.append((c, 1))
def result(self) -> str:
# Handle final run
if self.stack and self.stack[-1][1] >= self.k:
return ''.join(ch * cnt for ch, cnt in self.stack[:-1])
return ''.join(ch * cnt for ch, cnt in self.stack)
def remove_groups(s: str, k: int = 2) -> str:
cleaner = StreamingCleaner(k)
for char in s:
cleaner.feed(char)
return cleaner.result()
Edge Cases
- Empty string →
"" - No removals:
"abc"→"abc" - Complete erasure:
"aabbcc"→"" - Cascading merges:
"abbbaacc"with multiple rounds - Groups shorter than k survive when k > 2
Task 2: Boundary Node Collection
Algorithm Design
The problem asks for a specific concatenation: reverse(left_path) + [root] + right_path.
Key insight: Each boundary is a single greedy root-to-leaf walk, not a full subtree traversal.
- Left boundary walk: Start at
root.left. At each step, prefer the left child; if absent, take the right child. Stop at a leaf. - Right boundary walk: Start at
root.right. At each step, prefer the right child; if absent, take the left child. Stop at a leaf.
These paths are disjoint (one is entirely in the left subtree, the other entirely in the right subtree), so no node appears twice.
Algorithm:
- Walk the left boundary, collecting values top-down into a list
- Reverse that list
- Append the root value
- Walk the right boundary, appending values top-down
Complexity:
- Time: O(h) ⊆ O(n) — Each boundary walk follows at most h edges
- Space: O(h) — For storing the boundary paths (the output itself)
Implementation
from typing import List, Optional
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def boundary_mirror(root: Optional[TreeNode]) -> List[int]:
if not root:
return []
result = []
# Collect left boundary (top-down)
node = root.left
left_path = []
while node:
left_path.append(node.val)
node = node.left if node.left else node.right
# Add reversed left boundary
result.extend(reversed(left_path))
# Add root
result.append(root.val)
# Collect right boundary (top-down)
node = root.right
while node:
result.append(node.val)
node = node.right if node.right else node.left
return result
Edge Cases
- Empty tree →
[] - Single node →
[root.val] - Only left subtree → reverse(left_path) + [root]
- Only right subtree → [root] + right_path
- Paths that zig-zag (alternating between left and right children)
Common Mistakes
- Confusing "deepest leftmost leaf" with "leftmost node at maximum depth"—the boundary definition uses a greedy walk, not level-based selection
- Including the root in both boundary walks, causing duplication
- Attempting full tree traversal instead of simple path walks (O(n) instead of O(h))
- Not handling missing subtrees correctly
Summary
Task 1 uses a run-length stack to simulate cascading deletions in one pass. The key is recognizing that merges happen immediately after deletions.
Task 2 reduces to two simple path walks with list reversal. Recognize that "boundary" means a specific greedy path, not a subtree.
Both problems demonstrate the power of maintaining clean invariants and avoiding unnecessary work.