KatInterview

Two Warm-Ups: One-Deletion Palindrome and Column-Grouped Tree Output

Trees & GraphsModel answer
MediumModel answerTrees & Graphstwo-pointerspalindromebfs

Last 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, with 1 <= len(s) <= 100,000
  • Output: a boolean

Examples

  • s = "abca" returns true (removing 'b' or 'c' works)
  • s = "abc" returns false

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: root of 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.