Calculator - Amazon Top Interview Questions
Problem Statement :
Given a string s representing a mathematical expression with"+", "-", "/", and "*", evaluate and return the result. Note: "/" is integer division. Can you implement without using eval? Example 1 Input s = "1+2*4/6" Output 2 Explanation 1 + ((2 * 4) / 6) = 2
Solution :
Solution in C++ :
int cmp(char a, char b) {
int aa = (a == '+' || a == '-') ? 1 : 2;
int bb = (b == '+' || b == '-') ? 1 : 2;
return aa - bb;
}
int calc(stack<int>& sk, stack<char>& op) {
int b = sk.top();
sk.pop();
int a = sk.top();
sk.pop();
char c = op.top();
op.pop();
if (c == '+') return a + b;
if (c == '-') return a - b;
if (c == '*') return a * b;
if (c == '/') return (int)floor(1.0 * a / b);
assert(false);
return 0;
}
int solve(string s) {
stack<int> sk;
stack<char> op;
for (int i = 0, j = 0; j < s.size();) {
if (s[j] == '-') j++;
while (j < s.size() && isdigit(s[j])) j++;
int n = stoi(s.substr(i, j - i));
sk.push(n);
if (j == s.size()) {
while (!op.empty()) sk.push(calc(sk, op));
break;
} else {
if (op.empty() || cmp(s[j], op.top()) > 0) {
op.push(s[j]);
} else {
while (!op.empty() && cmp(s[j], op.top()) <= 0) {
sk.push(calc(sk, op));
}
op.push(s[j]);
}
}
j++;
i = j;
}
return sk.top();
}
Solution in Java :
import java.util.*;
class Solution {
private String str;
private int idx = 0;
public int solve(String s) {
if (s == null || s.length() == 0)
return 0;
s = "+" + s.trim();
List<Character> ops = new ArrayList<>();
List<Integer> list = new ArrayList<>();
str = s;
idx = 0;
String word = null;
while ((word = getToken()) != null) {
final char op = word.charAt(0);
String op2 = getToken();
int val = -1;
if (Character.isDigit(op2.charAt(0))) {
val = Integer.parseInt(op2);
} else {
val = Integer.parseInt(getToken());
if (op2.charAt(0) == '-')
val = -val;
}
switch (op) {
case '+':
ops.add(op);
list.add(val);
break;
case '-':
ops.add(op);
list.add(val);
break;
case '*':
list.set(list.size() - 1, list.get(list.size() - 1) * val);
break;
case '/':
double denominator = list.get(list.size() - 1);
denominator /= val;
list.set(list.size() - 1, (int) Math.floor(denominator));
break;
}
}
int res = 0;
for (int i = 0; i != list.size(); i++) {
char op = ops.get(i);
int val = list.get(i);
res += (op == '+' ? val : -val);
}
return res;
}
private String getToken() {
while (idx != str.length()) {
if (str.charAt(idx) == ' ') {
idx++;
continue;
} else {
if (Character.isDigit(str.charAt(idx))) {
int j = idx;
while (j + 1 != str.length() && Character.isDigit(str.charAt(j + 1))) j++;
String res = str.substring(idx, j + 1);
idx = j + 1;
return res;
} else {
return str.substring(idx, ++idx);
}
}
}
return null;
}
}
Solution in Python :
def inorder(s):
infix = []
operand = ""
prev_operator = "+"
for c in s:
if c not in "+-*/":
operand += c
elif prev_operator in "+-*/" and c == "-":
# negative number found!
operand += c
else:
infix.append(operand)
infix.append(c)
operand = ""
prev_operator = c
infix.append(operand)
return infix
# convert infix to postfix expression using a stack
def postorder(s):
# ops stack is storing the operators
ops = []
res = []
for c in s:
if c not in "+-/*":
res.append(int(c))
elif c in "/*" and len(ops) and ops[-1] in "+-" or len(ops) == 0:
ops.append(c)
else:
# while precedence of operator is greater than or equal
while len(ops) and (ops[-1] in "*/" or c in "+-"):
res.append(ops.pop())
ops.append(c)
while len(ops):
res.append(ops.pop())
return res
# postfix is easy to evaluate for CPU and easy to code for us!
def postorder_eval(postfix):
res = []
for c in postfix:
if isinstance(c, str):
b = int(res.pop())
a = int(res.pop())
if c == "+":
c = a + b
elif c == "-":
c = a - b
elif c == "*":
c = a * b
elif c == "/":
c = a // b
res.append(c)
else:
res.append(c)
return res[-1]
class Solution:
def solve(self, s):
infix = inorder(s)
print(infix)
postfix = postorder(infix)
print(postfix)
return postorder_eval(postfix)
View More Similar Problems
Self-Driving Bus
Treeland is a country with n cities and n - 1 roads. There is exactly one path between any two cities. The ruler of Treeland wants to implement a self-driving bus system and asks tree-loving Alex to plan the bus routes. Alex decides that each route must contain a subset of connected cities; a subset of cities is connected if the following two conditions are true: There is a path between ever
View Solution →Unique Colors
You are given an unrooted tree of n nodes numbered from 1 to n . Each node i has a color, ci. Let d( i , j ) be the number of different colors in the path between node i and node j. For each node i, calculate the value of sum, defined as follows: Your task is to print the value of sumi for each node 1 <= i <= n. Input Format The first line contains a single integer, n, denoti
View Solution →Fibonacci Numbers Tree
Shashank loves trees and math. He has a rooted tree, T , consisting of N nodes uniquely labeled with integers in the inclusive range [1 , N ]. The node labeled as 1 is the root node of tree , and each node in is associated with some positive integer value (all values are initially ). Let's define Fk as the Kth Fibonacci number. Shashank wants to perform 22 types of operations over his tree, T
View Solution →Pair Sums
Given an array, we define its value to be the value obtained by following these instructions: Write down all pairs of numbers from this array. Compute the product of each pair. Find the sum of all the products. For example, for a given array, for a given array [7,2 ,-1 ,2 ] Note that ( 7 , 2 ) is listed twice, one for each occurrence of 2. Given an array of integers, find the largest v
View Solution →Lazy White Falcon
White Falcon just solved the data structure problem below using heavy-light decomposition. Can you help her find a new solution that doesn't require implementing any fancy techniques? There are 2 types of query operations that can be performed on a tree: 1 u x: Assign x as the value of node u. 2 u v: Print the sum of the node values in the unique path from node u to node v. Given a tree wi
View Solution →Ticket to Ride
Simon received the board game Ticket to Ride as a birthday present. After playing it with his friends, he decides to come up with a strategy for the game. There are n cities on the map and n - 1 road plans. Each road plan consists of the following: Two cities which can be directly connected by a road. The length of the proposed road. The entire road plan is designed in such a way that if o
View Solution →