fork download
  1.  
  2. /*
  3. PROBLEM: Evaluate a Nested Math Expression
  4. FOLLOW-UP 2: Variable Number of Arguments
  5.  
  6. Functions:
  7. add(x1, x2, ..., xk)
  8. sub(x1, x2, ..., xk)
  9. mul(x1, x2, ..., xk)
  10. div(x1, x2, ..., xk)
  11. pow(x1, x2, ..., xk)
  12.  
  13. Examples:
  14. add(1,2,3,4) -> 10
  15. mul(2,3,4) -> 24
  16. sub(20,5,3) -> 12
  17. div(100,2,5) -> 10
  18. pow(2,3,2) -> 64
  19. add(1,mul(2,3,4),5) -> 30
  20.  
  21. ASSUMPTIONS:
  22. - Input is valid.
  23. - Every function has at least one argument.
  24. - add/mul combine all arguments.
  25. - sub/div/pow are evaluated left to right.
  26. - Unary operations return their only argument.
  27. - Division truncates toward zero after each step.
  28. - Exponents are nonnegative integers.
  29. - Intermediate results fit signed 32-bit integers.
  30.  
  31. APPROACH: TWO STACKS
  32.  
  33. names:
  34.   Stores frames containing:
  35.   { operation, startIndex }
  36.   Here startIndex reprsents elements in the values arr.
  37. values:
  38.   Stores integers and completed subexpression results.
  39.  
  40. When a function starts:
  41.   Save values.length as startIndex.
  42.  
  43. When ')' is encountered:
  44.   All values from startIndex onward are arguments
  45.   belonging to that function.
  46.  
  47.   Evaluate them from left to right.
  48.   Replace them with one result.
  49.  
  50. TIME: O(n), under fixed-width arithmetic assumptions.
  51. SPACE: O(d), where d is maximum nesting depth,
  52.   plus pending arguments; worst case O(n).
  53. */
  54.  
  55. function evaluateExpression(s) {
  56. const names = [];
  57. const values = [];
  58.  
  59. let i = 0;
  60.  
  61. function skipSpaces() {
  62. while (i < s.length && s[i] === ' ') {
  63. i++;
  64. }
  65. }
  66.  
  67. function isNumberStart(ch) {
  68. return ch === '-' || (ch >= '0' && ch <= '9');
  69. }
  70.  
  71. function parseNumber() {
  72. const start = i;
  73.  
  74. if (s[i] === '-') i++;
  75.  
  76. while (
  77. i < s.length &&
  78. s[i] >= '0' &&
  79. s[i] <= '9'
  80. ) {
  81. i++;
  82. }
  83.  
  84. return Number(s.slice(start, i));
  85. }
  86.  
  87. function parseOperation() {
  88. const operation = s.slice(i, i + 3);
  89. i += 3;
  90. return operation;
  91. }
  92.  
  93. // Apply one operation to two values.
  94. function applyCall(operation, x, y) {
  95. if (operation === 'add') return x + y;
  96. if (operation === 'sub') return x - y;
  97. if (operation === 'mul') return x * y;
  98. if (operation === 'div') return Math.trunc(x / y);
  99. if (operation === 'pow') return Math.pow(x, y);
  100. }
  101.  
  102. // Evaluate all arguments in their original order.
  103. function evaluateArgs(operation, args) {
  104. let result = args[0];
  105.  
  106. for (let j = 1; j < args.length; j++) {
  107. result = applyCall(operation, result, args[j]);
  108. }
  109.  
  110. return result;
  111. }
  112.  
  113. while (i < s.length) {
  114. skipSpaces();
  115.  
  116. if (i >= s.length) break;
  117.  
  118. // Case 1: Number
  119. if (isNumberStart(s[i])) {
  120. values.push(parseNumber());
  121. }
  122.  
  123. // Case 2: Function name
  124. else if (s[i] >= 'a' && s[i] <= 'z') {
  125. const operation = parseOperation();
  126.  
  127. // Remember where this function's arguments begin.
  128. names.push({
  129. operation,
  130. startIndex: values.length
  131. });
  132. }
  133.  
  134. // Case 3: Completed function call
  135. else if (s[i] === ')') {
  136. const frame = names.pop();
  137.  
  138. // Extract this function's arguments.
  139. // splice removes them from values.
  140. const args = values.splice(frame.startIndex);
  141.  
  142. // Evaluate arguments from left to right.
  143. const result = evaluateArgs(
  144. frame.operation,
  145. args
  146. );
  147.  
  148. // Replace all arguments with one result.
  149. values.push(result);
  150.  
  151. i++;
  152. }
  153.  
  154. // Case 4: Skip '(' and ','
  155. else {
  156. i++;
  157. }
  158. }
  159.  
  160. return values[0];
  161. }
  162.  
  163.  
  164. // ---------------- TEST HARNESS ----------------
  165.  
  166. const tests = [
  167. ["add(1,2,3,4)", 10],
  168. ["mul(2,3,4)", 24],
  169. ["sub(20,5,3)", 12],
  170. ["div(100,2,5)", 10],
  171. ["pow(2,3,2)", 64],
  172.  
  173. // Nested operations
  174. ["add(1,mul(2,3,4),5)", 30],
  175. ["sub(20,add(2,3),4)", 11],
  176. ["mul(add(1,2,3),sub(10,4,2))", 24],
  177.  
  178. // Unary functions
  179. ["add(5)", 5],
  180. ["mul(-3)", -3],
  181. ["sub(10)", 10],
  182.  
  183. // Negative division
  184. ["div(-20,3,2)", -3],
  185.  
  186. // Powers
  187. ["pow(2,0,3)", 1],
  188. ["pow(0,0)", 1],
  189.  
  190. // Standalone number
  191. ["42", 42],
  192.  
  193. // Whitespace
  194. ["add( 1 , 2 , mul( 3 , 4 ) )", 15]
  195. ];
  196.  
  197. tests.forEach(([input, expected], index) => {
  198. const actual = evaluateExpression(input);
  199.  
  200. console.log(
  201. `Test ${index + 1}: ` +
  202. (actual === expected ? "PASS" : "FAIL") +
  203. ` | Expected: ${expected}` +
  204. ` | Actual: ${actual}`
  205. );
  206. });
  207. /*
  208. TIME COMPLEXITY: O(n)
  209.  
  210. n = total length of the expression
  211. k = number of arguments in a particular function
  212.  
  213. 1. Parsing:
  214.   - Each character is processed once.
  215.   - Total = O(n).
  216.  
  217. 2. Extracting arguments:
  218.   - values.splice(startIndex) extracts k arguments.
  219.   - Cost per function = O(k).
  220.   - Across all functions, the total number of
  221.   argument positions is O(n).
  222.   - Total extraction cost = O(n).
  223.  
  224. 3. Evaluating arguments:
  225.   - evaluateArgs() processes k arguments.
  226.   - Cost per function = O(k).
  227.   - Across all functions = O(n).
  228.  
  229. 4. Arithmetic:
  230.   - Fixed-width operations are treated as O(1).
  231.   - Math.pow() is treated as O(1) for this problem.
  232.  
  233. OVERALL TIME = O(n).
  234.  
  235.  
  236. SPACE COMPLEXITY: O(n)
  237.  
  238. d = maximum nesting depth
  239.  
  240. 1. names stack:
  241.   - Stores one frame per unfinished function.
  242.   - O(d) space.
  243.  
  244. 2. values stack:
  245.   - Stores arguments and intermediate results.
  246.   - A single function can have O(n) arguments.
  247.   - O(n) space.
  248.  
  249. 3. Temporary args array:
  250.   - splice() can extract O(n) arguments.
  251.   - O(n) temporary space.
  252.  
  253. OVERALL AUXILIARY SPACE = O(n).
  254.  
  255. IMPORTANT DIFFERENCE:
  256.  
  257. Original problem (exactly 2 arguments):
  258.   Space = O(d)
  259.  
  260. Follow-up (variable number of arguments):
  261.   Space = O(n)
  262.  
  263. Even when d = 1, a function such as
  264. add(1,1,1,1,...,1) can require O(n) space.
  265. */
  266.  
Success #stdin #stdout 0.03s 5636KB
stdin
Standard input is empty
stdout
Test 1: PASS | Expected: 10 | Actual: 10
Test 2: PASS | Expected: 24 | Actual: 24
Test 3: PASS | Expected: 12 | Actual: 12
Test 4: PASS | Expected: 10 | Actual: 10
Test 5: PASS | Expected: 64 | Actual: 64
Test 6: PASS | Expected: 30 | Actual: 30
Test 7: PASS | Expected: 11 | Actual: 11
Test 8: PASS | Expected: 24 | Actual: 24
Test 9: PASS | Expected: 5 | Actual: 5
Test 10: PASS | Expected: -3 | Actual: -3
Test 11: PASS | Expected: 10 | Actual: 10
Test 12: PASS | Expected: -3 | Actual: -3
Test 13: PASS | Expected: 1 | Actual: 1
Test 14: PASS | Expected: 1 | Actual: 1
Test 15: PASS | Expected: 42 | Actual: 42
Test 16: PASS | Expected: 15 | Actual: 15