Priority Queue Scheduler + Expression Evaluator
Data Structure DesignAuto-graded · 18 test casesLast updated
Tests heap-based priority scheduling with tie-breaking and recursive-descent expression parsing with variable substitution.
You will implement two mini-systems inside a single function and return both results together.
Part 1: Job Queue with Priority and Timing
You are given a list of jobs that are pre-loaded into a queue at startup. Each job is described by three values: a string job_id, an integer priority, and an integer arrival_time.
After the initial load, a sequence of operations is applied one at a time:
"add_task"— insert a new job into the queue. The corresponding entry inoperation_argsis[job_id, priority, arrival_time]."get_next_task"— remove and record the job that should run next. The corresponding entry inoperation_argsis[].
The job that runs next is always the one with the highest priority. When two jobs share the same priority, the one with the smaller arrival_time runs first. If two jobs share both priority and arrival time, the one that was inserted earlier (by insertion order across all additions, including the initial load) runs first.
Every "get_next_task" call appends its result to a list called processed. If the queue is empty when "get_next_task" is called, append None.
Part 2: Arithmetic Expression with Named Variables
You are also given a dictionary var_map mapping variable names to integer values, and a string expr containing an arithmetic expression.
Evaluate expr and return its integer result. The expression may contain:
- Non-negative integer literals (possibly multi-digit).
- Variable names made of letters, digits, and underscores, where the first character is a letter or underscore.
- The operators
+(addition) and*(multiplication), with standard precedence:*binds more tightly than+. - Parentheses
()to override precedence. - Any amount of whitespace between tokens.
If any variable that appears in the expression is not present in var_map, return -1 for the expression value — even if the missing variable's contribution would evaluate to zero under ordinary arithmetic.
Return Value
Return a single dictionary with exactly two keys:
{
"processed": <list of job_id strings and/or None values>,
"expression_value": <integer>
}
Constraints
- Number of pre-loaded jobs plus
"add_task"operations: up to 10^5 total. - Number of operations: up to 10^5.
priorityandarrival_timeare non-negative integers.- Expression length: up to 10^4 characters.
- Integer literals in the expression are non-negative.
- Variable names contain only alphanumeric characters and underscores.
- Operator precedence follows standard arithmetic:
*before+; parentheses override. - Left-to-right associativity for operators of equal precedence.
- Each
"get_next_task"on an empty queue producesNone(no error).
Examples
Example 1
Input: run_job_queue_and_eval([['T1', 10, 1], ['T2', 20, 2], ['T3', 10, 0]], ['get_next_task', 'get_next_task', 'get_next_task'], [[], [], []], {}, '0')
Output: {'processed': ['T2', 'T3', 'T1'], 'expression_value': 0}
Example 2
Input: run_job_queue_and_eval([], ['add_task', 'add_task', 'get_next_task', 'get_next_task'], [['A', 5, 10], ['B', 5, 3], [], []], {'x': 3}, 'x + 5 * 2')
Output: {'processed': ['B', 'A'], 'expression_value': 13}
Example 3
Input: run_job_queue_and_eval([['old', 1, 5]], ['get_next_task', 'get_next_task', 'add_task', 'get_next_task'], [[], [], ['new', 9, 8], []], {'a': 5, 'b': 10}, '(a + b) * 2')
Output: {'processed': ['old', None, 'new'], 'expression_value': 30}
Hints
Hint 1
For the job queue, Python's heapq is a min-heap. Think about how to negate or reorder the key tuple so that the 'best' job naturally ends up at the top of the heap.
Hint 2
A sequence counter incremented on every insertion gives you a stable third tie-breaker without ever comparing job_id strings — this also lets the heap avoid type errors when priorities and arrival times are equal.
Hint 3
For the expression evaluator, model the grammar in three layers — expression handles +, term handles *, and factor handles literals, variables, and parenthesised sub-expressions — and substitute variables as you parse rather than in a separate pass.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Part 1: Job Queue
The core requirement is a dynamic max-priority queue with a two-level tie-breaker. Python's heapq module provides an efficient min-heap, so the key insight is to engineer a tuple that sorts in exactly the right order under the default min semantics:
(-priority, arrival_time, sequence, job_id)
- Negating
prioritymaps "highest priority first" to "smallest key first", which is what a min-heap delivers. arrival_timeis kept positive. Among equal priorities, smaller arrival times sort earlier, which is the desired behavior.sequenceis a counter that increases by one on every insertion (initial load and subsequent"add_task"operations together). It guarantees a unique numeric third field, so Python never has to comparejob_idstrings. This avoids type errors and gives insertion-order semantics when both priority and arrival time are equal.
Every "get_next_task" call pops index [3] (the job_id) from the smallest tuple currently in the heap, or appends None if the heap is empty.
Complexity: O(log N) per insertion and per removal. Space O(N).
Part 2: Expression Evaluator
The expression grammar has two precedence levels (+ below *) plus parentheses. A recursive-descent parser encodes this directly as three mutually recursive functions:
parse_expression → handles + (lowest precedence)
parse_term → handles * (higher precedence)
parse_factor → handles atoms: literals, variables, (sub-expressions)
Because each layer only consumes the operator it owns and delegates everything else downward, operator precedence falls out of the call structure with no explicit precedence table needed. Left-associativity is achieved by the while True loops inside parse_expression and parse_term.
Variable substitution happens inside parse_factor at the moment an identifier is read. If the name is absent from var_map, a missing flag is set and 0 is returned so parsing can continue to completion. After the full parse, a set flag unconditionally replaces the numeric result with -1. This ensures that a missing variable in any position — even one multiplied by zero — still produces -1.
Complexity: O(L) time where L is the expression length; each character is consumed exactly once. O(D) space for the call stack, where D is the maximum nesting depth of parentheses.
Edge Cases
"get_next_task"on an empty queue →Noneinprocessed, no exception.- Two jobs with identical priority and arrival time → resolved by
sequence(insertion order). "add_task"operations interleaved with"get_next_task"operations → handled correctly because the heap is dynamic.- Multi-digit numbers and multi-character variable names → both parsers use
whileloops to consume full tokens. - Whitespace anywhere in the expression →
skip_spaces()is called before every token. - A missing variable inside parentheses or under a
* 0factor → still returns-1.
Reference Solution
import heapq
from typing import Dict, List
def run_job_queue_and_eval(
tasks: List[List],
operations: List[str],
operation_args: List[List],
var_map: Dict[str, int],
expr: str,
) -> Dict[str, object]:
# ------------------------------------------------------------------ #
# Part 1: priority job queue #
# ------------------------------------------------------------------ #
heap: list = []
sequence = 0
for job_id, priority, arrival_time in tasks:
heapq.heappush(heap, (-priority, arrival_time, sequence, job_id))
sequence += 1
processed = []
for op, args in zip(operations, operation_args):
if op == "add_task":
job_id, priority, arrival_time = args
heapq.heappush(heap, (-priority, arrival_time, sequence, job_id))
sequence += 1
elif op == "get_next_task":
processed.append(heapq.heappop(heap)[3] if heap else None)
# ------------------------------------------------------------------ #
# Part 2: recursive-descent expression evaluator #
# ------------------------------------------------------------------ #
pos = 0
missing = False
text = expr
def skip_spaces() -> None:
nonlocal pos
while pos < len(text) and text[pos].isspace():
pos += 1
def parse_factor() -> int:
nonlocal pos, missing
skip_spaces()
if pos < len(text) and text[pos] == '(':
pos += 1
value = parse_expression()
skip_spaces()
if pos < len(text) and text[pos] == ')':
pos += 1
return value
if pos < len(text) and text[pos].isdigit():
start = pos
while pos < len(text) and text[pos].isdigit():
pos += 1
return int(text[start:pos])
start = pos
while pos < len(text) and (text[pos].isalnum() or text[pos] == '_'):
pos += 1
name = text[start:pos]
if name not in var_map:
missing = True
return 0
return var_map[name]
def parse_term() -> int:
nonlocal pos
value = parse_factor()
while True:
skip_spaces()
if pos >= len(text) or text[pos] != '*':
return value
pos += 1
value *= parse_factor()
def parse_expression() -> int:
nonlocal pos
value = parse_term()
while True:
skip_spaces()
if pos >= len(text) or text[pos] != '+':
return value
pos += 1
value += parse_term()
expression_value = parse_expression()
if missing:
expression_value = -1
return {"processed": processed, "expression_value": expression_value}