Bracket Matching, Interval Union, and Expression Parsing
Stacks & QueuesAuto-graded · 22 test casesLast updated
Tests stack-based bracket validation, interval merging with endpoint semantics, and arithmetic evaluation with unary operators.
You will implement a single function that solves three independent subproblems and returns their results in a dictionary.
Subproblem 1: Bracket Validation
Given a string s containing only the characters (, ), [, ], {, }, determine whether the brackets are properly matched and nested.
- Return
Trueif every opening bracket has a corresponding closing bracket of the same type in the correct order. - Return
Falseotherwise. - An empty string is considered valid.
Subproblem 2: Interval Union
Given a list of intervals where each interval is represented as [start, end, left_closed, right_closed]:
startandendare integers withstart <= endleft_closedandright_closedare booleans indicating whether the interval includes its left and right endpoints
Compute the union of all intervals and return a minimal sorted list of non-overlapping intervals in the same format.
Merging rules:
- Two intervals should merge if they overlap or touch
- Intervals with
prev_end > cur_startalways merge - Intervals with
prev_end == cur_startmerge if and only if at least one endpoint at that position is closed (eitherprevis right-closed ORcuris left-closed) - An interval
[a, a, False, False],[a, a, True, False], or[a, a, False, True]represents an empty set and should be removed - An interval
[a, a, True, True]represents a single point and should be kept
Subproblem 3: Arithmetic Expression Evaluation
Given a string expr containing:
- Non-negative integers
- Binary operators:
+,-,*,/ - Parentheses:
(,) - Unary minus (e.g.,
-3,1+-2,2*(-3+4)) - Arbitrary whitespace
Compute and return the integer result of the expression.
Rules:
- Division truncates toward zero (e.g.,
7 / -2equals-3) - A minus sign is unary when it appears at the start, after an operator, or after an opening parenthesis
- You may assume the expression is valid and all intermediate results fit in a 32-bit signed integer
Return Value
Return a dictionary with three keys:
{
'valid_brackets': bool,
'merged_intervals': List[List], # each inner list is [start, end, left_closed, right_closed]
'expression_result': int
}
Constraints
0 <= len(s) <= 10^40 <= len(intervals) <= 10^4-10^9 <= start, end <= 10^9for each interval0 <= len(expr) <= 10^4- Expression contains only valid characters as described
- All three subproblems should be solved efficiently:
- Bracket validation: O(n) time, O(n) space
- Interval merging: O(n log n) time, O(n) space
- Expression evaluation: O(n) time, O(n) space
Examples
Example 1
Input: process_three_tasks('([]{})', [[1, 3, True, True], [3, 5, True, False]], '2*(-3+4)')
Output: {'valid_brackets': True, 'merged_intervals': [[1, 5, True, False]], 'expression_result': 2}
Example 2
Input: process_three_tasks('([)]', [[1, 3, True, False], [3, 5, False, True]], '-3+5')
Output: {'valid_brackets': False, 'merged_intervals': [[1, 3, True, False], [3, 5, False, True]], 'expression_result': 2}
Example 3
Input: process_three_tasks('', [], '1+-2')
Output: {'valid_brackets': True, 'merged_intervals': [], 'expression_result': -1}
Hints
Hint 1
For bracket validation, use a stack to track unmatched opening brackets. Each closing bracket must match the most recent unmatched opener.
Hint 2
When merging intervals, first remove empty sets (where start equals end but at least one side is open), then sort by start position with ties broken by whether the left side is closed.
Hint 3
For expression evaluation, handle unary minus by checking whether an operand precedes the minus sign. Use recursive descent or a two-stack approach to respect operator precedence.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem combines three classic algorithms that each test a different aspect of implementation skill.
Part 1: Bracket Validation
Scan the string from left to right using a stack. Push each opening bracket onto the stack. When a closing bracket appears, check that the stack is non-empty and its top element is the matching opener. If not, the string is invalid. After processing all characters, the string is valid only if the stack is empty (all openers were closed).
Why it works: The stack maintains unmatched opening brackets in the order they appear. Proper nesting requires that each closer matches the most recently opened unmatched bracket, which is always at the top of the stack.
Part 2: Interval Merging with Endpoint Semantics
First, filter out empty intervals: those where start == end but at least one endpoint is open. Next, sort the remaining intervals by start position, with ties broken so that closed-left intervals come before open-left intervals at the same start point.
Sweep through the sorted list. For each interval, check if it should merge with the last interval in the result:
- Merge if
prev_end > cur_start - Merge if
prev_end == cur_startAND (the previous interval is right-closed OR the current interval is left-closed)
When merging:
- Keep the earlier start
- If
cur_end > prev_end, extend tocur_endand adopt its right-closedness - If
cur_end == prev_end, the merged interval is right-closed if either input is right-closed - Otherwise the current interval is fully contained; keep the previous interval unchanged
Why it works: After sorting, any interval that can merge with the current merged block must start at or after the block's start. The merge condition precisely captures whether the intervals overlap or touch according to endpoint rules. The scan produces a minimal sorted output because we never revisit earlier blocks.
Part 3: Expression Evaluation
Use recursive descent parsing with three mutually recursive functions:
parse_expression: handles+and-(lowest precedence)parse_term: handles*and/(higher precedence)number_or_group: parses numbers, parenthesized subexpressions, and unary operators
The key challenge is unary minus. We detect it by consuming consecutive + and - signs before a number or opening parenthesis, flipping the sign for each - encountered. This correctly handles cases like --3 (positive 3) and 1+-2 (1 plus negative 2).
For division, Python's // operator floors the result, but the problem requires truncation toward zero. We compute abs(a) // abs(b) and then negate the result if the operands have opposite signs.
Why it works: Recursive descent naturally respects operator precedence. By parsing terms (products and quotients) before adding or subtracting them, we ensure 2+3*4 evaluates as 2+(3*4). Handling unary operators in number_or_group ensures they bind tighter than binary operators, so -3*2 evaluates as (-3)*2.
Complexity
- Bracket validation: O(n) time, O(n) space for the stack in the worst case (all opening brackets).
- Interval merging: O(n log n) time for sorting, O(n) space for the sorted copy and output.
- Expression evaluation: O(n) time (each character visited once), O(n) space for the recursion stack in deeply nested expressions.
Solution
from typing import Dict, List
def process_three_tasks(s: str, intervals: List[List], expr: str) -> Dict[str, object]:
# Subproblem 1: Bracket validation
pairs = {')': '(', ']': '[', '}': '{'}
stack = []
valid = True
for ch in s:
if ch in '([{':
stack.append(ch)
elif not stack or stack.pop() != pairs[ch]:
valid = False
break
valid = valid and not stack
# Subproblem 2: Interval merging
ordered = sorted(intervals, key=lambda x: (x[0], not x[2], x[1], not x[3]))
merged = []
for start, end, left_closed, right_closed in ordered:
# Remove empty intervals
if start == end and not (left_closed and right_closed):
continue
current = [start, end, left_closed, right_closed]
if not merged:
merged.append(current)
continue
prev = merged[-1]
joins = prev[1] > start or (prev[1] == start and (prev[3] or left_closed))
if not joins:
merged.append(current)
continue
if end > prev[1]:
prev[1] = end
prev[3] = right_closed
elif end == prev[1]:
prev[3] = prev[3] or right_closed
# Subproblem 3: Expression evaluation
text = expr
pos = 0
n = len(text)
def skip_spaces():
nonlocal pos
while pos < n and text[pos].isspace():
pos += 1
def number_or_group():
nonlocal pos
skip_spaces()
sign = 1
while pos < n and text[pos] in '+-':
if text[pos] == '-':
sign = -sign
pos += 1
skip_spaces()
if pos < n and text[pos] == '(':
pos += 1
value = parse_expression()
skip_spaces()
pos += 1
return sign * value
start = pos
while pos < n and text[pos].isdigit():
pos += 1
return sign * int(text[start:pos])
def parse_term():
nonlocal pos
value = number_or_group()
while True:
skip_spaces()
if pos >= n or text[pos] not in '*/':
return value
op = text[pos]
pos += 1
rhs = number_or_group()
if op == '*':
value *= rhs
else:
quotient = abs(value) // abs(rhs)
value = -quotient if (value < 0) != (rhs < 0) else quotient
def parse_expression():
nonlocal pos
value = parse_term()
while True:
skip_spaces()
if pos >= n or text[pos] not in '+-':
return value
op = text[pos]
pos += 1
rhs = parse_term()
value = value + rhs if op == '+' else value - rhs
result = parse_expression()
return {
'valid_brackets': valid,
'merged_intervals': merged,
'expression_result': result,
}