cswork / libraryOpen practice workspace

Coding questions · Meta

Solve tree traversal and two-pointer problems

Solve tree traversal and two-pointer problems evaluates algorithm design, data structures, correctness, complexity, edge cases, and implementation details in a realistic interview setting. A strong answer states assumptions, handles edge cases, explains trade-offs, and shows how to validate the result clearly.

Implement the following independent problems:

  1. Vertical columns: Given a binary tree, return lists of node values grouped by vertical columns from leftmost to rightmost. For nodes in the same column and row, preserve left-to-right order of appearance. State time and space complexities. Follow-up: support streaming insertions and queries.
  2. Right-side view: Given a binary tree, return the sequence of nodes visible from the right side. Clarify tie-breaking and how to handle missing children. Provide BFS and DFS solutions and their complexities.
  3. Two-sum pairs count: Given a sorted integer array and target T, count the number of unique index pairs (i, j), i < j, such that nums[i] + nums[j] == T. Achieve O(n) time and O(1) extra space; handle duplicates robustly.
  4. Zigzag levels: Given a binary tree, output its level-order traversal with alternating left-to-right and right-to-left ordering per level. Discuss trade-offs between deque-based BFS and DFS with level tracking.

What a Strong Answer Covers

  • A clear algorithm with the right data structures and enough pseudocode or code-level detail to implement it.
  • A correctness argument that explains why the algorithm covers all required cases.
  • Time and space complexity, plus at least one alternative approach when relevant.
  • Focused tests for normal cases, edge cases, and failure modes.

Follow-up Questions

  • How would the approach change if the input were streaming or too large for memory?
  • What invariants would you assert in production code?
  • Which tests would catch off-by-one, duplicate, or tie-breaking bugs?

Vertical Order Traversal of a Binary Tree

Given a binary tree (provided as a level-order array tree using null/None for missing children, LeetCode-style), return the vertical order traversal of its node values.

Group node values by their column index, where the root is column 0, a left child is column - 1, and a right child is column + 1. Return a list of columns ordered from the leftmost column to the rightmost column. Within a single column, order nodes first by their row (depth, smaller depth first); for nodes that share the same row and column, preserve their left-to-right order of appearance during the traversal.

State the time and space complexity. Follow-up: how would you support streaming insertions and repeated column queries?

Example: tree = [3,9,20,null,null,15,7] returns [[9],[3,15],[20],[7]].

Constraints

  • 0 <= number of nodes <= 10^4
  • Node values fit in a 32-bit signed integer
  • tree is a valid level-order encoding where every present node lists both child slots (None for missing)

Hints

  1. Track a (column, row) coordinate for every node: root is (0,0); a left child is (col-1, row+1), a right child is (col+1, row+1).
  2. Use BFS so that nodes are visited top-to-bottom and left-to-right, giving you a natural tie-break order for same (row, column) nodes.
  3. Bucket nodes by column, then emit columns in increasing column index; within a column sort by (row, appearance order).

Binary Tree Right Side View

Given a binary tree (provided as a level-order array tree using null/None for missing children, LeetCode-style), imagine standing on the right side of the tree. Return the values of the nodes visible from the right side, ordered from top to bottom.

A node is visible from the right at a given depth if it is the last (rightmost) node reached at that depth. Missing children simply produce no node at that position. Provide both a BFS solution (take the last node of each level) and a DFS solution (visit right subtree first, record the first node seen at each new depth); both run in O(n) time.

Example: tree = [1,2,3,null,5,null,4] returns [1,3,4].

Constraints

  • 0 <= number of nodes <= 10^4
  • Node values fit in a 32-bit signed integer
  • tree is a valid level-order encoding (None for missing children)

Hints

  1. BFS level by level: the last node you dequeue on each level is the one visible from the right.
  2. DFS alternative: recurse right subtree before left, and record a node the first time you reach a new depth.
  3. Missing children contribute nothing — only push real (non-None) children into the queue.

Count Unique Two-Sum Pairs in a Sorted Array

Given a sorted (ascending) integer array nums and an integer target, count the number of unique value pairs (a, b) with a + b == target, where a and b are taken from two different indices i < j. Two pairs are considered the same if they use the same pair of values, so duplicate values must not inflate the count — for example, with many copies of the same value the pair is counted once.

Achieve O(n) time and O(1) extra space using the two-pointer technique on the sorted array, and handle duplicates robustly. Return the count.

Example: nums = [1,1,2,2,3,3], target = 4 returns 2 (the value pairs (1,3) and (2,2)).

Constraints

  • 0 <= len(nums) <= 10^5
  • nums is sorted in non-decreasing order
  • -10^9 <= nums[i], target <= 10^9

Hints

  1. Use two pointers from both ends; if the sum is too small move left in, if too large move right in.
  2. On a match, skip ALL duplicates of the left value and ALL duplicates of the right value so each distinct value pair is counted exactly once.
  3. When the two pointers land on equal values that sum to target (e.g. target/2), that is a single valid pair — count it once and stop.

Binary Tree Zigzag Level Order Traversal

Given a binary tree (provided as a level-order array tree using null/None for missing children, LeetCode-style), return its zigzag level-order traversal: the first level is read left-to-right, the next right-to-left, alternating per level.

Return a list of levels, each level being the list of node values in the required direction. Discuss the trade-offs between a deque-based BFS (reverse alternate levels) and a DFS that tracks the level index.

Example: tree = [3,9,20,null,null,15,7] returns [[3],[20,9],[15,7]].

Constraints

  • 0 <= number of nodes <= 10^4
  • Node values fit in a 32-bit signed integer
  • tree is a valid level-order encoding (None for missing children)

Hints

  1. Do a normal BFS, collecting each level's values into a buffer.
  2. Keep a boolean that flips every level; reverse the buffer on right-to-left levels before appending.
  3. DFS alternative: recurse with a depth index and append to result[depth], inserting at the front when depth is odd — but BFS is usually clearer.

Solution

Solution Alignment

The prompt asks for an implementation-level answer. The safest way to present it is to define the state, maintain clear invariants, then walk through complexity and tests.

Problem Restatement

Implement the following independent problems: 1) Vertical columns: Given a binary tree, return lists of node values grouped by vertical columns from leftmost to rightmost. For nodes in the same column and row, preserve left-to-right order of appearance. State time and space complexities. Follow-up: support streaming insertions and queries. 2) Right-side view: Given a binary tree, return the sequence of nodes visible from the right side. Clarify tie-breaking and how to handle missing children. Provide BFS and DFS solutions and their complexities. 3) Two-sum pairs count: Given a sorted integer array and target T, count the number of unique index pairs (i, j), i < j, such that nums[i] + nums[j]...

Recommended Approach

Choose traversal based on the required view or aggregate. DFS is natural for subtree computations and reconstruction; BFS is natural for level order or side views. Keep per-depth or per-position state when the output depends on columns, rows, or depths.

Correctness

The implementation should maintain an invariant after each loop or operation that directly matches the problem statement. At termination, that invariant implies the returned value has considered every valid candidate exactly once, or has preserved the required data-structure state after every API call.

Complexity

Most tree traversals are O(n) time and O(h) recursion stack for DFS or O(w) queue space for BFS, where h is height and w is maximum width.

Edge Cases and Tests

Empty tree, one node, skewed tree, duplicate values when reconstruction assumes uniqueness, deep recursion, and tie-breaking for same row/column nodes.