Implement topological sort and tree boundary traversal
SnowflakeSoftware Engineer · Technical ScreenLast updated
These tasks evaluate core competencies in directed graph algorithms (topological ordering and cycle detection) and binary tree traversals (boundary identification and leaf enumeration), testing understanding of dependency modeling and traversal patterns.
You are given two separate coding tasks.
Problem A — Order courses with prerequisites
You have n courses labeled 0..n-1 and a list of prerequisite pairs prerequisites, where each pair [a, b] means to take course a, you must first take course b.
Task: Return any valid ordering of all courses that satisfies prerequisites. If it is impossible (because of a cycle), return an empty list.
Input:
n(integer)prerequisites(list of pairs)
Output:
- A list of length
nrepresenting a valid order, or[]if no order exists.
Constraints (typical):
1 ≤ n ≤ 10^50 ≤ len(prerequisites) ≤ 2*10^5
Notes:
- Implement the algorithm yourself (e.g., topological sort).
- Be prepared to write a few basic tests (e.g., cycle case, disconnected graph).
Problem B — Boundary traversal of a (complete/balanced) binary tree
You are given the root of a binary tree. The tree is guaranteed to be complete and balanced (interview variant constraint), but your solution may work for any binary tree.
Define the boundary of the tree in anti-clockwise order as:
- The root (once).
- The left boundary (excluding leaves): from
root.leftgoing downward, always taking the next boundary node. - All leaf nodes from left to right.
- The right boundary (excluding leaves): from
root.rightgoing downward, collected top-down but output bottom-up.
Task: Return a list of node values in boundary order, with no duplicates.
Input:
rootof a binary tree
Output:
- List of integers representing the boundary traversal.
Edge cases to consider:
- Single-node tree
- Root has only one child
- Trees where left/right boundary paths include missing children (even if the interview variant says complete)
Complexity target:
- Time
O(N), spaceO(H)(recursion) orO(N)worst case depending on implementation.
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.