KatInterview

Group Deletion Stack and Boundary Path Collection

Stacks & QueuesModel answer
MediumModel answerStacks & Queuesstackbinary-treestring-manipulation

Last 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:

  1. 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)
  2. Add the root value
  3. 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?