KatInterview

Topological Task Scheduler and Strict Expression Parser

Trees & GraphsModel answer
HardModel answerTrees & Graphstopological-sortgraph-algorithmsexpression-parser

Last 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:

  1. Detail both BFS (Kahn's algorithm) and DFS approaches.
  2. Explain how cycle detection operates under each approach.
  3. Discuss time and space complexities.
  4. 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:
    1. Exponentiation ^ (highest precedence, right-associative).
    2. Unary minus - (prefix, right-associative, precedence level 3).
    3. Multiplication *, Integer Division /, Modulo % (precedence level 2, left-associative).
    4. Addition +, Subtraction - (precedence level 1, left-associative).
  • Parentheses: ( and ) can override standard precedence and may be nested arbitrarily deep.

Semantics & Edge Cases:

  • Note precedence conventions: -2^2 evaluates to -4 (since ^ binds tighter than unary minus), whereas (-2)^2 evaluates to 4.
  • 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.