PracHub
QuestionsPremiumLearningGuidesCheatsheetNEWCareers

Quick Overview

This question evaluates skill in parsing and evaluating arithmetic expressions with integer operands and the operators +, -, *, and /, focusing on operator precedence and evaluation order within the Coding & Algorithms domain.

  • Medium
  • Amazon
  • Coding & Algorithms
  • Software Engineer

Implement basic calculator

Company: Amazon

Role: Software Engineer

Category: Coding & Algorithms

Difficulty: Medium

Interview Round: Take-home Project

##### Question LeetCode 227. Basic Calculator II – implement an arithmetic expression evaluator supporting +, -, *, / and integer operands https://leetcode.com/problems/basic-calculator-ii/description/

Quick Answer: This question evaluates skill in parsing and evaluating arithmetic expressions with integer operands and the operators +, -, *, and /, focusing on operator precedence and evaluation order within the Coding & Algorithms domain.

Given a string s representing a valid arithmetic expression containing non-negative integers, '+', '-', '*', '/', and spaces, compute its value. The expression contains no parentheses. Division between two integers should truncate toward zero. Return the evaluated integer result.

Constraints

  • 1 <= len(s) <= 100000
  • s contains only digits, '+', '-', '*', '/', and spaces
  • The expression is valid and contains no parentheses
  • Operands are non-negative integers (no unary plus/minus)
  • Integer division truncates toward zero
  • The final result fits in a 32-bit signed integer

Examples

Input: 3+2*2

Expected Output:

Input: 14 - 3*4 + 5 / 2

Expected Output:

Input: 3/2

Expected Output:

Input: 2-5*2

Expected Output:

Input: 0*10+5/2

Expected Output:

Input: 42

Expected Output:

Solution

def evaluate_expression(s: str) -> int:
    total = 0
    last = 0
    num = 0
    op = '+'  # previous operator
    for ch in s + '+':  # sentinel to flush the last number
        if ch == ' ':
            continue
        if ch.isdigit():
            num = num * 10 + (ord(ch) - ord('0'))
        elif ch in '+-*/':
            if op == '+':
                total += last
                last = num
            elif op == '-':
                total += last
                last = -num
            elif op == '*':
                last = last * num
            elif op == '/':
                # Truncate toward zero
                last = int(last / num)
            op = ch
            num = 0
    return total + last
Explanation
Perform a single left-to-right scan, maintaining: (1) total: sum of fully-resolved terms; (2) last: the most recent term not yet added to total; (3) num: the current number being parsed; (4) op: the previous operator. On encountering an operator (or at the end via a sentinel), apply the previous operator to 'last' and 'num'. For +/-, move the previous 'last' into 'total' and reset 'last' to +/-num. For */ apply the operation directly to 'last' to respect precedence. Finally, return total + last. Use int(a / b) to truncate toward zero for division.

Time complexity: O(n). Space complexity: O(1).

Hints

  1. Scan the string once while tracking the current number and the previous operator.
  2. Use a 'last term' variable to handle * and / precedence without a stack.
  3. Apply the previous operator when you meet a new operator or reach the end.
  4. To truncate toward zero in Python, use int(a / b) for division.
Last updated: Mar 29, 2026

Loading coding console...

PracHub

Master your tech interviews with 7,500+ real questions from top companies.

Product

  • Questions
  • Learning Tracks
  • Interview Guides
  • Resources
  • Premium
  • Careers
  • For Universities
  • Student Access

Browse

  • By Company
  • By Role
  • By Category
  • Topic Hubs
  • SQL Questions
  • Compare Platforms
  • Discord Community

Support

  • support@prachub.com
  • (916) 541-4762

Legal

  • Privacy Policy
  • Terms of Service
  • About Us

© 2026 PracHub. All rights reserved.

Related Coding Questions

  • Find Valid IP Addresses in Files - Amazon (medium)
  • Implement Optimal Bucket Batching - Amazon (hard)
  • Implement Cache and Rotate Matrix - Amazon (medium)
  • Find Longest Activatable Server Streak - Amazon (hard)
  • Build the Largest Available Sequence - Amazon (medium)