Evaluate Expressions with Operator Precedence
Solve this ProblemEasy10 min
Topics
BasicsOperators
Companies
TCSInfosysWipro
Given three integers
a, b and c, return the values of four expressions in order: a + b * c, (a + b) * c, a - b - c and a - (b - c).
Arithmetic operators do not simply run left to right. Operator precedenceOperator PrecedenceThe ranking that decides which operator is applied first: *, / and % come before + and −. decides which operator goes first, associativityAssociativityFor operators of equal precedence, the direction they group in. + and − group left to right. breaks ties between operators of the same rank, and brackets override both. The four expressions are chosen in pairs so each pair differs only by where the brackets are.
Test Case 1:
Input:a = 2, b = 3, c = 4
Output:[14,20,-5,3]
Explanation:2 + 3 × 4 multiplies first (14); brackets change it to 5 × 4 = 20; subtraction runs left to right (−5); brackets on the right give 2 − (−1) = 3.
Test Case 2:
Input:a = 10, b = 0, c = 7
Output:[10,70,3,17]
Explanation:With b = 0 the product b × c vanishes, but (a + b) × c does not.
Constraints
- ◆
0 ≤ a, b, c ≤ 1000
Try the Dry Run
Approach & Solutions
Step by Step with Temporary VariablesGood
Make the order of evaluation completely explicit: compute every sub-expression in its own variable, in the order the language would. For a + b * c that means the product first; for (a + b) * c the sum first; for a - b - c the left subtraction first; for a - (b - c) the bracket first.
Time
O(1)Space
O(1)Java
class Solution {
public int[] precedenceResults(int a, int b, int c) {
int product = b * c;
int first = a + product;
int sum = a + b;
int second = sum * c;
int leftPart = a - b;
int third = leftPart - c;
int inner = b - c;
int fourth = a - inner;
return new int[] {first, second, third, fourth};
}
}Let Precedence Do the WorkOptimal
Write each expression directly and trust the language's rules: * before + and −, operators of equal rank from left to right, and brackets first of all. The results match the step-by-step version exactly, with no temporary variables.
Time
O(1)Space
O(1)Java
class Solution {
public int[] precedenceResults(int a, int b, int c) {
int first = a + b * c;
int second = (a + b) * c;
int third = a - b - c;
int fourth = a - (b - c);
return new int[] {first, second, third, fourth};
}
}