Basic Calculator IV — LeetCode 770 Python Solution

HardStackRecursionHash TableMathString
Problem
#770
Pattern
Stack
Reading time
2 min

The problem

Given an expression such as expression = "e + 8 - a + 5" and an evaluation map such as {"e": 1} (given in terms of evalvars = ["e"] and evalints = [1]), return a list of tokens representing the simplified expression, such as ["-1*a","14"] An expression alternates chunks and symbols, with a space separating each chunk and symbol. A chunk is either an expression in parentheses, a variable, or a non-negative integer.

Example

Input
expression = "e + 8 - a + 5", evalvars = ["e"], evalints = [1]
Output
["-1*a","14"]

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Stack

When the most recent unresolved thing is the one that matters, use a stack. LeetCode 770. Basic Calculator IV is filed here because LeetCode tags it Stack, which is the vocabulary this hub collects.

The stack guide has the Python template for the pattern and the 194 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 770. Basic Calculator IV?
LeetCode 770. Basic Calculator IV is rated Hard on LeetCode.
What is the time complexity of LeetCode 770. Basic Calculator IV?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 770. Basic Calculator IV?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 770. Basic Calculator IV cover?
LeetCode 770. Basic Calculator IV is tagged Stack, Recursion, Hash Table, Math and String on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview