Here is the full interview question "Evaluate String Expression - Uber Coding Interview | ShowOffer" from Uber on ShowOffer.io:
Problem Statement: Given a string expression, evaluate the expression and return the result. The expression can contain numbers, addition (+), subtraction (-), multiplication (*), and division (/) operations. The expression can also contain parentheses to indicate the order of operations.
Examples:
Input: "3 + 4 - 1 * 3" Output: 4
Input: "2 * (3 + 3) / 2" Output: 5
Input: "(2 + 3) * 4 / 2" Output: 10
Constraints:
Hints:
Solution: To solve this problem, you can use a stack-based approach to evaluate the expression while considering the order of operations. Here's a high-level algorithm:
Here's a Python implementation of the algorithm:
`python def evaluate_expression(expression): def apply_operator(op, a, b): if op == '+': return a + b if op == '-': return a - b if op == '*': return a * b if op == '/': return a // b
def precedence(op):
if op in ('+', '-'): return 1
if op in ('*', '/'): return 2
return 0
num_stack = []
op_stack = []
i = 0
while i < len(expression):
if expression[i].isdigit():
j = i
while j < len(expression) and expression[j].isdigit():
j += 1
num_stack.append(int(expression[i:j]))
i = j - 1
elif expression[i] == ' ':
i += 1
elif expression[i] == '(':
op_stack.append(expression[i])
i += 1
elif expression[i] == ')':
while op_stack[-1] != '(':
num_stack.append(apply_operator(op_stack.pop(), num_stack.pop(), num_stack.pop()))
op_stack.pop()
i += 1
else:
while (len(op_stack) > 0 and precedence(op_stack[-1]) >= precedence(expression[i])):
num_stack.append(apply_operator(op_stack.pop(), num_stack.pop(), num_stack.pop()))
op_stack.append(expression[i])
i += 1
while len(op_stack) > 0:
num_stack.append(apply_operator(op_stack.pop(), num_stack.pop(), num_stack.pop()))
return num_stack[-1]
`
This solution should be able to evaluate the given string expression and return the correct result.