KatInterview

Lone-Parity Filter and Leftmost Node Per Tree Depth

Trees & GraphsModel answer
EasyModel answerTrees & Graphsbfsbinary-treelevel-order

Last updated

Write one function that returns the elements whose even/odd class appears exactly once in an array, plus the first node's value at every depth of a binary tree.

Implement a single function solve(nums, root) that handles two small, independent tasks and returns both results as a tuple.

Task A: Elements with a lone parity

You are given a list of integers nums. Split the numbers into two classes: even and odd. Return a list of every element that is the only member of its class. In other words, if the array contains exactly one even number, that number is included. If it contains exactly one odd number, that number is included too. Both can apply at once. Keep the original order.

Examples:

  • [1, 3, 5, 2, 7] returns [2], since 2 is the sole even value and the odds are plentiful.
  • [4, 7] returns [4, 7], since each class has exactly one member.
  • [2, 4, 6] returns [], since no class has exactly one member.

Task B: Leftmost value on each depth

You are given the root of a binary tree. For each depth (root is depth 0), find the node that is furthest to the left among all nodes at that depth, and collect its value. Return these values from the shallowest depth to the deepest. The node does not need to be a left child. If a depth holds only a right child, that node counts.

Example tree:

    1
   / \
  2   3
 / \
4   5

Result: [1, 2, 4]

If the root is None, the result is an empty list.

Signature

class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

def solve(nums, root):
    # return (lone_parity_values, leftmost_per_depth)
    pass

Constraints

  • 1 <= len(nums) <= 10^4
  • The tree has between 0 and 10^4 nodes.
  • Aim for O(N) time, where N is the size of the relevant input.

What to cover in your answer

Explain your approach for each task, argue why it is correct, state time and space complexity, give code, and mention the edge cases you would test.

Hints

Hint 1

For the array task, a single counting pass tells you how many evens and odds exist. An element qualifies exactly when the count of its own class is 1.

Hint 2

Be careful with the case where both classes have exactly one member, and with negative numbers: in some languages `-3 % 2` is `-1`, so test oddness with `x % 2 != 0` or `x & 1`.

Hint 3

For the tree task, traverse level by level with a queue. Before expanding a level, record the front of the queue, and snapshot the queue length so you process exactly one level per iteration.