Topological Task Scheduler and Strict Expression Parser
Trees & GraphsModel answerLast updated
Solve a task dependency ordering problem via topological sort and build an expression evaluator supporting custom operator precedence, unary signs, and overflow checks.
This problem consists of two distinct components.
Part 1: Task Scheduling Order
You are given an integer $n$ (where $0 \le n \le 200,000$) denoting tasks labeled from $0$ to $n - 1$. You are also given a list of directed dependencies prereqs, where each entry $[a, b]$ specifies that task $b$ must be finished prior to starting task $a$.
Write a function plan(n, prereqs) that returns a valid sequential execution order containing all $n$ tasks. If no valid sequence can execute every task (for instance, due to a cyclical dependency), return an empty array [].
Requirements & Follow-ups:
- Detail both BFS (Kahn's algorithm) and DFS approaches.
- Explain how cycle detection operates under each approach.
- Discuss time and space complexities.
- Explain how you would adapt the algorithm if:
- You need the lexicographically smallest task ordering.
- You need to detect if the valid schedule is unique.
- Edge dependencies are delivered via an online stream.
Part 2: Math Expression Evaluator
Write a function evaluate(s) that receives an arithmetic expression string $s$ and returns its evaluated 64-bit signed integer result. Raise an error (or exception) if the expression is syntactically invalid or encounters runtime arithmetic issues.
Parsing Rules:
- Operands: Non-negative integer literals.
- Whitespace: Spaces may appear anywhere and should be ignored.
- Operators & Precedence:
- Exponentiation
^(highest precedence, right-associative). - Unary minus
-(prefix, right-associative, precedence level 3). - Multiplication
*, Integer Division/, Modulo%(precedence level 2, left-associative). - Addition
+, Subtraction-(precedence level 1, left-associative).
- Exponentiation
- Parentheses:
(and)can override standard precedence and may be nested arbitrarily deep.
Semantics & Edge Cases:
- Note precedence conventions:
-2^2evaluates to-4(since^binds tighter than unary minus), whereas(-2)^2evaluates to4. - Division
/must truncate toward zero (e.g.,-7 / 3 == -2). - Modulo
%follows the identity $a - b \times \text{trunc}(a / b)$, matching C/Java behavior. - Raise an error for:
- Division or modulo by zero.
- Negative exponents (e.g., $2^{-3}$).
- Any intermediate or final evaluation overflowing the 64-bit signed integer range $[-2^{63}, 2^{63} - 1]$.
- Syntax errors (mismatched parentheses, consecutive binary operators, trailing operators, invalid characters).
Time complexity should be $O(|s|)$ and auxiliary space $O(|s|)$.
Hints
Hint 1
For Part 1, construct adjacency list edges from b to a. Kahn's algorithm yields an in-degree zero queue, while DFS requires tracking 3 node states (unvisited, visiting, visited) to spot back-edges.
Hint 2
For Part 2, track a boolean flag `expect_operand` to distinguish unary minus from binary subtraction while scanning characters.
Hint 3
Use the Shunting-Yard algorithm with two stacks (one for numeric values, one for operators) to achieve O(N) evaluation without hitting deep recursion stack limits.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Part 1: Task Scheduling Order
Approach & Graph Representation
We model the system as a directed graph where each task $0 \dots n-1$ is a node. A dependency pair $[a, b]$ means $b \to a$ (node $b$ must be processed before node $a$). A valid execution schedule is a topological sort of this directed acyclic graph (DAG).
1. BFS Approach (Kahn's Algorithm)
- Build an adjacency list
adjmapping $b \to [a_1, a_2, \dots]$ and calculate the in-degree for every vertex $a$. - Push all nodes with an in-degree of $0$ into a processing queue.
- Continually dequeue node $u$, append $u$ to the result schedule, and decrease the in-degree of all target nodes $v \in \text{adj}[u]$ by $1$.
- Whenever a target node $v$'s in-degree drops to $0$, push it into the queue.
- Cycle Detection: If the output schedule contains fewer than $n$ elements when the queue empties, at least one cycle exists. Return
[].
2. DFS Approach (Coloring Algorithm)
- Maintain a state array for each node:
UNVISITED (0),VISITING (1),VISITED (2). - Traverse unvisited nodes. Perform a post-order traversal.
- If traversing an edge leads to a node currently marked as
VISITING, a back-edge exists, indicating a cycle. - When a node finishes traversing all descendants, mark it
VISITEDand push it to a result array. - Reverse the result array at the end to retrieve the correct dependency ordering. Note: To prevent stack overflow with $n = 200,000$ in non-tail-call optimized languages like Python, use an explicit iterative stack.
Complexity Analysis
- Time Complexity: $O(n + m)$ where $m = |\text{prereqs}|$. Every vertex and edge is processed a constant number of times.
- Space Complexity: $O(n + m)$ to store the graph representation and order output.
Follow-Up Scenarios
- Lexicographically Smallest Order: Replace the standard FIFO queue in Kahn's algorithm with a Minimum Heap (Priority Queue). The time complexity becomes $O((n + m) \log n)$.
- Uniqueness Check: A topological order is unique if and only if at every step of Kahn's algorithm, the queue contains at most one element. If the queue size exceeds $1$ at any point, multiple valid schedules exist.
- Dynamic / Streaming Edges: If edges arrive continuously and dynamically, running $O(n + m)$ full topological sorts becomes infeasible. We can maintain a dynamic topological ordering using algorithms like Pearce-Kelly, which incrementally reorders only the affected topological window upon inserting an edge in $O(k)$ time (where $k$ is the size of the reordered subgraph).
Part 2: Math Expression Evaluator
Parsing Strategy (Shunting-Yard Adaptation)
We parse the input string $s$ using a two-stack system: a Value Stack and an Operator Stack.
To handle operator precedence, associativity, and unary operators without dynamic memory overhead or deep recursion risks, we maintain a boolean state variable expect_operand = True.
- If
expect_operandisTrueand we encounter-, the operator is a unary negation (neg). - If
expect_operandisFalseand we encounter-, the operator is a binary subtraction.
Operator Precedence Rules
^: Precedence 4, Right-Associative.neg(unary-) : Precedence 3, Right-Associative.*,/,%: Precedence 2, Left-Associative.+,-: Precedence 1, Left-Associative.
Evaluator Implementation
INT_MIN = -(1 << 63)
INT_MAX = (1 << 63) - 1
class ParseError(Exception):
pass
def plan(n: int, prereqs: list[list[int]]) -> list[int]:
"""Part 1: BFS Kahn's Algorithm for Topological Ordering."""
adj = [[] for _ in range(n)]
indegree = [0] * n
for dest, src in prereqs:
adj[src].append(dest)
indegree[dest] += 1
queue = [i for i in range(n) if indegree[i] == 0]
head = 0
while head < len(queue):
curr = queue[head]
head += 1
for neighbor in adj[curr]:
indegree[neighbor] -= 1
if indegree[neighbor] == 0:
queue.append(neighbor)
return queue if len(queue) == n else []
def evaluate(s: str) -> int:
"""Part 2: Expression Parser using double-stack Shunting-Yard logic."""
prec = {'+': 1, '-': 1, '*': 2, '/': 2, '%': 2, 'neg': 3, '^': 4}
right_assoc = {'^', 'neg'}
def check_range(val: int) -> int:
if not (INT_MIN <= val <= INT_MAX):
raise ParseError("64-bit Signed Integer Overflow")
return val
def apply_op(ops: list[str], vals: list[int]):
if not ops:
raise ParseError("Missing operator")
op = ops.pop()
if op == 'neg':
if not vals:
raise ParseError("Invalid unary operation")
vals.append(check_range(-vals.pop()))
return
if len(vals) < 2:
raise ParseError("Insufficient operands")
b = vals.pop()
a = vals.pop()
if op == '+':
res = a + b
elif op == '-':
res = a - b
elif op == '*':
res = a * b
elif op == '/':
if b == 0:
raise ParseError("Division by zero")
# Truncate toward zero
res = int(float(a) / b) if a * b < 0 and a % b != 0 else a // b
elif op == '%':
if b == 0:
raise ParseError("Modulo by zero")
# Match C/Java dividend sign convention
res = a - b * (int(float(a) / b) if a * b < 0 and a % b != 0 else a // b)
elif op == '^':
if b < 0:
raise ParseError("Negative exponent not supported")
if b == 0:
res = 1
elif abs(a) > 1 and b >= 64:
raise ParseError("Exponentiation overflow")
else:
res = pow(a, b)
else:
raise ParseError(f"Unknown operator {op}")
vals.append(check_range(res))
ops = []
vals = []
expect_operand = True
i = 0
n = len(s)
while i < n:
c = s[i]
if c.isspace():
i += 1
continue
if c.isdigit():
if not expect_operand:
raise ParseError("Unexpected integer literal")
start = i
while i < n and s[i].isdigit():
i += 1
num = int(s[start:i])
vals.append(check_range(num))
expect_operand = False
continue
if c == '(':
if not expect_operand:
raise ParseError("Unexpected open parenthesis")
ops.append('(')
i += 1
continue
if c == ')':
if expect_operand:
raise ParseError("Unexpected closing parenthesis")
while ops and ops[-1] != '(':
apply_op(ops, vals)
if not ops:
raise ParseError("Unmatched closing parenthesis")
ops.pop() # Remove '('
i += 1
continue
# Operator processing (+, -, *, /, %, ^)
if c in "+-*/%^":
if c == '-' and expect_operand:
op_type = 'neg'
else:
if expect_operand:
raise ParseError(f"Unexpected binary operator {c}")
op_type = c
curr_prec = prec[op_type]
while ops and ops[-1] != '(':
top_op = ops[-1]
top_prec = prec[top_op]
if (top_prec > curr_prec) or (top_prec == curr_prec and op_type not in right_assoc):
apply_op(ops, vals)
else:
break
ops.append(op_type)
expect_operand = True
i += 1
continue
raise ParseError(f"Invalid character encountered: {c}")
if expect_operand:
raise ParseError("Expression ended unexpectedly")
while ops:
if ops[-1] == '(':
raise ParseError("Unmatched open parenthesis")
apply_op(ops, vals)
if len(vals) != 1:
raise ParseError("Malformed expression")
return vals[0]
Complexity & Edge Case Coverage
- Time Complexity: $O(|s|)$. Every character is evaluated in a single linear pass. Each value and operator is pushed and popped at most once.
- Space Complexity: $O(|s|)$ to store the evaluation stack.
| Test Scenario | Input String | Expected Result / Outcome |
|---|---|---|
| Precedence & Exponentiation | -2^2 | -4 |
| Parenthesization override | (-2)^2 | 4 |
| Negative integer division | -7 / 3 | -2 (Truncates to zero) |
| C-style Modulo | -7 % 3 | -1 |
| Complex Right Associativity | 2 ^ 3 ^ 2 | 512 ($2^9$) |
| Intermediate 64-bit Overflow | 9223372036854775807 + 1 | Raises ParseError |
| Mismatched Parentheses | ((3 + 2) | Raises ParseError |