Lone-Parity Filter and Leftmost Node Per Tree Depth
Trees & GraphsModel answerLast 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
0and10^4nodes. - 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.
Model answer
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Overview
The two tasks are independent, so I would write two helpers and have solve call both. Before coding I would confirm the contract: output order follows input order, both classes can be lone at the same time, and an empty tree yields an empty list.
Task A: lone parity
Idea. Parity splits the array into two groups. An element is in the answer exactly when its group has size 1. So:
- Pass one: count evens. Odds are
len(nums) - evens. - Pass two: keep each element whose group count equals 1.
Why it is correct. The counts are exact group sizes, and the filter applies the definition directly to every element, so nothing is missed and nothing extra is kept. At most two elements can qualify (one per class).
Cases I would test.
[1, 3, 5, 2, 7]gives[2].[4, 7]gives[4, 7], the case where both classes are lone.[2, 4, 6]gives[].[9]gives[9].- Negative values such as
[-3, 2, 4]give[-3].
Complexity. O(N) time and O(1) extra space beyond the output (at most 2 items).
Common mistakes. Assuming there is always exactly one outlier, so the [4, 7] case breaks. Using x % 2 == 1 for oddness, which fails for negatives in Java or C++. Python is safe because -3 % 2 == 1, but x % 2 != 0 is portable.
Task B: leftmost node per depth
Idea. Use breadth-first search, one level at a time.
- If
rootisNone, return[]. - Put the root in a queue.
- While the queue is not empty, the front element is the leftmost node of the current depth, so record its value.
- Pop exactly
len(queue)nodes (the size taken before adding children), pushing left child then right child.
Why it is correct. Invariant: when a level begins, the queue holds exactly the nodes of that depth in left-to-right order. The root level satisfies this trivially. Because each level is processed left to right and children are appended left before right, the next level is also in left-to-right order. Hence the front of the queue is always the leftmost node of that depth.
Note that the answer is not "follow left pointers". For
1
/ \
2 3
\
5
the result is [1, 2, 5], because 5 is the only node at depth 2 even though it is a right child.
Complexity. O(N) time, since each node enters and leaves the queue once. O(W) space where W is the maximum width, up to about N/2 for a complete tree.
Edge cases. Empty tree returns []. A single node returns [root.val]. Skewed trees in either direction return every value.
Code
from collections import deque
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def lone_parity(nums):
evens = sum(1 for x in nums if x % 2 == 0)
odds = len(nums) - evens
out = []
for x in nums:
group = evens if x % 2 == 0 else odds
if group == 1:
out.append(x)
return out
def leftmost_per_depth(root):
if root is None:
return []
out = []
q = deque([root])
while q:
out.append(q[0].val)
for _ in range(len(q)):
node = q.popleft()
if node.left:
q.append(node.left)
if node.right:
q.append(node.right)
return out
def solve(nums, root):
return lone_parity(nums), leftmost_per_depth(root)
Trade-offs and follow-ups
DFS alternative. Do a preorder traversal that visits the left child before the right. The first node reached at each depth is the leftmost, detected when depth == len(result). Space is O(H) for height H.
- Balanced tree: H is about log N while W is about N/2, so DFS uses less memory.
- Skewed tree: W is 1 while H is N, so BFS uses less memory.
Recursion limit. With up to 10^4 nodes, a skewed tree can exceed Python's default recursion limit of about 1,000. Use an explicit stack (push right child first so left is popped first) or raise the limit.
def leftmost_dfs(root):
out = []
stack = [(root, 0)] if root else []
while stack:
node, d = stack.pop()
if d == len(out):
out.append(node.val)
if node.right:
stack.append((node.right, d + 1))
if node.left:
stack.append((node.left, d + 1))
return out
Indices instead of values. For Task A, reuse the counts and emit i from enumerate rather than x. A single-pass variant stores the last index seen per parity and validates it only when that class count ends at 1.
Rightmost view. Record the last node of each level in BFS, or mirror the DFS to visit right first.
Final checklist
- Clarify tie cases and empty input first.
- Snapshot the level size before enqueueing children.
- Be explicit about modulo behavior on negatives.
- Walk through
[4, 7],[2, 4, 6], an empty tree, and the right-child-only level before declaring it done.