Two Warm-Ups: One-Deletion Palindrome and Column-Grouped Tree Output
Trees & GraphsModel answerLast updated
Decide whether a string becomes a palindrome after removing at most one character, then group a binary tree's node values by column using level-order tie-breaking.
This prompt has two independent coding problems. No code needs to run. Be ready to describe your approach, trace the examples, and justify the time and space complexity.
Problem A: Palindrome with a single removal allowed
You are given a string s of lowercase English letters. Return true if s is a palindrome after removing zero or one character, and false otherwise.
- Input:
s, with1 <= len(s) <= 100,000 - Output: a boolean
Examples
s = "abca"returnstrue(removing'b'or'c'works)s = "abc"returnsfalse
Problem B: Group tree values by column
Given the root of a binary tree, produce its vertical grouping.
Columns are numbered like this:
- The root is in column
0. - A left child is in column
parent - 1. - A right child is in column
parent + 1.
Return the groups from the leftmost column to the rightmost. Inside a group, values go from top to bottom. If two nodes share both row and column, they appear in the order a standard left-to-right level-order (BFS) traversal would visit them.
- Input:
rootof a binary tree, with up to about 10,000 to 100,000 nodes - Output:
List[List[int]]
Example
The root is 3. Its left child is 9 and its right child is 8. Node 9 has children 4 and 0. Node 8 has children 1 and 7.
Expected output: [[4], [9], [3, 0, 1], [8], [7]]
For both problems, state your algorithm, explain why it is correct, give time and space complexity, and list the edge cases you would test.
Hints
Hint 1
For Problem A, walk two pointers inward from both ends. Think about what you are forced to do at the first pair that disagrees, and how many choices you have there.
Hint 2
At the first mismatch, only two characters can be the one you remove: the left one or the right one. After removing one, the rest must be a perfect palindrome. Do not commit to one side greedily just because a neighbor happens to match. Try both.
Hint 3
For Problem B, store each node together with its column while traversing. Ask which traversal order already visits nodes top to bottom and left to right, so the tie-break rule costs nothing. Track the smallest and largest column seen so you never need to sort keys.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Problem A: Palindrome after at most one removal
Approach
Place l = 0 and r = len(s) - 1 and move inward while s[l] == s[r]. Matching pairs are already symmetric, and removing either character of a matching pair never helps the remaining comparisons, so we keep them.
At the first mismatch we must spend the removal. One of the two mismatched characters has to go, so there are exactly two candidates:
- Remove
s[l]: check whethers[l+1..r]is a palindrome. - Remove
s[r]: check whethers[l..r-1]is a palindrome.
Return true if either check succeeds. If the pointers meet without any mismatch, the string is already a palindrome, so return true.
Why both branches are needed
A tempting shortcut is "if s[l+1] == s[r], skip the left character, otherwise skip the right." This is wrong when both neighbors match. Take s = "abaab". The ends a and b mismatch. Here s[l+1] = 'b' equals s[r], and s[r-1] = 'a' equals s[l], so a greedy rule has no principled way to choose. Removing the left a gives "baab", which is a palindrome. Removing the right b gives "abaa", which is not. Only trying both branches is safe.
Complexity
- Time: O(n). The main scan is at most n/2 steps. It branches once, and each branch scans at most n characters. The total is a small constant times n, with no exponential blowup because we branch only once.
- Space: O(1) if you compare by index and never slice.
Code
def valid_palindrome(s: str) -> bool:
def is_pal(i: int, j: int) -> bool:
while i < j:
if s[i] != s[j]:
return False
i += 1
j -= 1
return True
l, r = 0, len(s) - 1
while l < r:
if s[l] != s[r]:
return is_pal(l + 1, r) or is_pal(l, r - 1)
l += 1
r -= 1
return True
Edge cases
- Length 1 or 2: always
true. - Already a palindrome:
true, and the removal is never used. "abca": mismatch atbvsc. Removingcleaves"aba", which works."abc": both branches fail, sofalse.
Likely follow-up
"What if up to k removals are allowed?" A recursive version with a budget costs up to O(n * 2^k). A more robust approach is DP for the longest palindromic subsequence. The answer is true when n - LPS <= k, at O(n^2) time.
Problem B: Grouping node values by column
Approach
Run an iterative BFS where each queue entry is (node, column). When a node is dequeued, append its value to a dictionary entry for its column. Enqueue the left child with column - 1 and the right child with column + 1. Keep running min_col and max_col. At the end, output the lists for every column from min_col to max_col.
Why it satisfies the ordering rules
- Top to bottom: BFS finishes all nodes of depth d before any node of depth d+1, so values within a column are appended in non-decreasing row order.
- Same row and column: the required tie-break is literally BFS order, left to right. Plain BFS already produces it, so no sorting is needed.
- Left to right across columns: a child is exactly one column from its parent, so the used columns form a contiguous range with no gaps. Iterating from
min_coltomax_colis enough, and sorting the dictionary keys is unnecessary.
Why not DFS
DFS may visit a deep left node before a shallower right node in the same column, which breaks the top-to-bottom rule. You would need to store (row, visit_order, value) and sort each column, adding O(n log n). Recursive DFS can also overflow the stack on a skewed tree of 100,000 nodes. BFS avoids both problems.
Be aware of a well-known sibling problem where ties in the same row and column are broken by value instead of BFS order. That version does require sorting, so read the tie rule carefully before reusing a solution.
Complexity
- Time: O(n). Each node is enqueued and dequeued once, and building the output is O(number of columns) plus O(n) for the lists.
- Space: O(n) for the dictionary and the queue. The queue holds at most one level's width at a time.
Code
from collections import defaultdict, deque
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 column_groups(root: Optional[TreeNode]) -> List[List[int]]:
if root is None:
return []
by_col = defaultdict(list)
lo = hi = 0
q = deque([(root, 0)])
while q:
node, col = q.popleft()
by_col[col].append(node.val)
lo = min(lo, col)
hi = max(hi, col)
if node.left:
q.append((node.left, col - 1))
if node.right:
q.append((node.right, col + 1))
return [by_col[c] for c in range(lo, hi + 1)]
Trace on the example
Dequeue order is 3, 9, 8, 4, 0, 1, 7, with columns 0, -1, 1, -2, 0, 0, 2.
- Column -2 gets
[4]. - Column -1 gets
[9]. - Column 0 gets
[3, 0, 1]. Nodes0and1share row 2, and0comes first because its parent9is dequeued before8. - Column 1 gets
[8]. - Column 2 gets
[7].
Result: [[4], [9], [3, 0, 1], [8], [7]].
Edge cases
- Empty tree: return
[]. - Single node:
[[val]]. - Fully skewed tree (all left or all right): n columns with one value each. The iterative BFS handles this without recursion limits.
- Many nodes sharing one column, such as a zig-zag shape: the BFS order guarantees correct row ordering.
Common mistakes
- Sorting dictionary keys on every call instead of tracking min and max, which adds an unnecessary O(w log w).
- Using DFS and getting the top-to-bottom order wrong.
- In Problem A, committing to one side at the first mismatch.
- In Problem A, creating substrings in the checks, which costs extra memory and time.