Basic Calculator
Given a string s representing a valid expression Return the result of evaluating the expression Example: s = "1 + 1" => 2 Example: s = " 2-1 + 2 " => 3 Example: s = "(1+(4+5+2)-3)+(6+8)" => 23
I scan once with a stack. A parenthesis saves the running total and sign, and the closing one restores them.
Examples
You write
calculate(s: str)
Example 1
- Input
- s = "1 + 1"
- returns
- 2
Example 2
- Input
- s = " 2-1 + 2 "
- returns
- 3
The pattern behind it
Strings
I reach for it when
- The input is text and the answer is a count, a substring or a new string.
- You need to compare, reverse or rebuild characters.
Say this before you type. Say which array pattern the string is hiding before you touch a character.
All 51 Strings problemsStack
I reach for it when
- Things must close in the reverse order they opened.
- You need the nearest earlier or later item that is bigger or smaller.
Say this before you type. Say what each item on the stack is waiting for, and what lets you pop it.
All 17 Stack problems
Meet Coco
Coco is an AI study partner, not a person. She listens while you explain your code, asks what a line does and never hands you the fix. Sign in free to type with Coco, up to a daily limit. The editor and Run stay open without an account. Anyone can open the editor and run their code.
Prep guides that list this problem
Our company tags come from public interview write-ups. None of these is a confirmed question.