fork download
  1.  
  2. /*
  3. PROBLEM: Evaluate a Nested Math Expression
  4.  
  5. Given a valid expression containing:
  6. add(x,y), sub(x,y), mul(x,y), div(x,y), pow(x,y)
  7.  
  8. Arguments can be integers or nested expressions.
  9.  
  10. Examples:
  11. add(1,sub(1,0)) => 2
  12. sub(div(-7,2),pow(-2,3)) => 5
  13.  
  14. PATTERN: Recursive Descent Parsing
  15.  
  16. TIME: O(n)
  17. - Shared index i only moves forward.
  18. - Every character is processed O(1) times.
  19. - pow() uses binary exponentiation, O(log exp).
  20. - Since exp fits in 32 bits, each pow call takes
  21.   at most 31 iterations, so total time is O(n).
  22.  
  23. SPACE: O(d)
  24. - d = maximum nesting depth.
  25. - Recursive calls use O(d) stack space.
  26. - Worst case d = O(n), giving O(n) space.
  27.  
  28. NOTE:
  29. Extremely deep nesting may exceed JavaScript's
  30. recursion limit. Use an iterative stack parser
  31. for guaranteed support of all valid inputs.
  32. */
  33.  
  34. function evaluateExpression(s) {
  35. let i = 0;
  36.  
  37. // 1. Skip whitespace
  38. function skipSpaces() {
  39. while (i < s.length && s[i] === " ") {
  40. i++;
  41. }
  42. }
  43.  
  44. // 2. Check whether expression begins with a number
  45. function isNumberStart(ch) {
  46. return ch === "-" || (ch >= "0" && ch <= "9");
  47. }
  48.  
  49. // 3. Parse a complete integer
  50. function parseNumber() {
  51. const start = i;
  52.  
  53. if (s[i] === "-") {
  54. i++;
  55. }
  56.  
  57. while (
  58. i < s.length &&
  59. s[i] >= "0" &&
  60. s[i] <= "9"
  61. ) {
  62. i++;
  63. }
  64.  
  65. return Number(s.slice(start, i));
  66. }
  67.  
  68. // 4. Parse operation: add, sub, mul, div, pow
  69. function parseOperation() {
  70. const operation = s.slice(i, i + 3);
  71. i += 3;
  72. return operation;
  73. }
  74.  
  75. // 5. Parse and evaluate ONE complete expression
  76. function parse() {
  77. skipSpaces();
  78.  
  79. // BASE CASE: Integer
  80. if (isNumberStart(s[i])) {
  81. return parseNumber();
  82. }
  83.  
  84. // RECURSIVE CASE: Function call
  85. const operation = parseOperation();
  86.  
  87. skipSpaces();
  88. i++; // Skip '('
  89.  
  90. // Evaluate first argument
  91. const left = parse();
  92.  
  93. skipSpaces();
  94. i++; // Skip ','
  95.  
  96. // Evaluate second argument
  97. const right = parse();
  98.  
  99. skipSpaces();
  100. i++; // Skip ')'
  101.  
  102. // Combine evaluated arguments
  103. return apply(operation, left, right);
  104. }
  105.  
  106. // 6. Apply arithmetic operation
  107. function apply(operation, a, b) {
  108. if (operation === "add") return a + b;
  109. if (operation === "sub") return a - b;
  110. if (operation === "mul") return a * b;
  111. if (operation === "div") return Math.trunc(a / b);
  112. if (operation === "pow") return power(a, b);
  113. }
  114.  
  115. // 7. Binary exponentiation: O(log exp) time, O(1) space
  116. function power(base, exp) {
  117. let result = 1;
  118.  
  119. while (exp > 0) {
  120. if (exp % 2 === 1) {
  121. result *= base;
  122. }
  123.  
  124. exp = Math.floor(exp / 2);
  125.  
  126. if (exp > 0) {
  127. base *= base;
  128. }
  129. }
  130.  
  131. return result;
  132. }
  133.  
  134. return parse();
  135. }
  136.  
  137.  
  138. // =========================================
  139. // IDEONE TEST HARNESS
  140. // =========================================
  141.  
  142. const tests = [
  143. // Basic operations
  144. { input: "add(1,2)", expected: 3 },
  145. { input: "sub(5,3)", expected: 2 },
  146. { input: "mul(4,5)", expected: 20 },
  147. { input: "div(10,3)", expected: 3 },
  148. { input: "pow(2,5)", expected: 32 },
  149.  
  150. // Nested expressions
  151. { input: "add(1,sub(1,0))", expected: 2 },
  152. { input: "add(sub(5,2),sub(1,4))", expected: 0 },
  153. { input: "sub(add(7,8),sub(3,1))", expected: 13 },
  154. { input: "add(5,mul(2,pow(5,2)))", expected: 55 },
  155.  
  156. // Negative numbers and division
  157. { input: "sub(div(-7, 2), pow(-2, 3))", expected: 5 },
  158. { input: "div(-7,2)", expected: -3 },
  159. { input: "div(7,-2)", expected: -3 },
  160. { input: "div(-7,-2)", expected: 3 },
  161.  
  162. // Edge cases
  163. { input: "-42", expected: -42 },
  164. { input: "0", expected: 0 },
  165. { input: "pow(0,0)", expected: 1 },
  166. { input: "pow(5,0)", expected: 1 },
  167. { input: "pow(-2,3)", expected: -8 },
  168. { input: "add( 10 , mul( 2 , 3 ) )", expected: 16 },
  169.  
  170. // Both arguments nested
  171. { input: "sub(add(5,2),mul(2,3))", expected: 1 }
  172. ];
  173.  
  174. let passed = 0;
  175.  
  176. tests.forEach(({ input, expected }, index) => {
  177. try {
  178. const actual = evaluateExpression(input);
  179. const ok = actual === expected;
  180.  
  181. if (ok) passed++;
  182.  
  183. console.log(
  184. `Test ${index + 1}: ${ok ? "PASS" : "FAIL"}` +
  185. ` | Input: ${input}` +
  186. ` | Expected: ${expected}` +
  187. ` | Actual: ${actual}`
  188. );
  189. } catch (error) {
  190. console.log(
  191. `Test ${index + 1}: FAIL` +
  192. ` | Input: ${input}` +
  193. ` | Error: ${error.message}`
  194. );
  195. }
  196. });
  197.  
  198. console.log(`\nPassed ${passed}/${tests.length} tests`);
  199.  
Success #stdin #stdout 0.03s 5680KB
stdin
Standard input is empty
stdout
Test 1: PASS | Input: add(1,2) | Expected: 3 | Actual: 3
Test 2: PASS | Input: sub(5,3) | Expected: 2 | Actual: 2
Test 3: PASS | Input: mul(4,5) | Expected: 20 | Actual: 20
Test 4: PASS | Input: div(10,3) | Expected: 3 | Actual: 3
Test 5: PASS | Input: pow(2,5) | Expected: 32 | Actual: 32
Test 6: PASS | Input: add(1,sub(1,0)) | Expected: 2 | Actual: 2
Test 7: PASS | Input: add(sub(5,2),sub(1,4)) | Expected: 0 | Actual: 0
Test 8: PASS | Input: sub(add(7,8),sub(3,1)) | Expected: 13 | Actual: 13
Test 9: PASS | Input: add(5,mul(2,pow(5,2))) | Expected: 55 | Actual: 55
Test 10: PASS | Input: sub(div(-7, 2), pow(-2, 3)) | Expected: 5 | Actual: 5
Test 11: PASS | Input: div(-7,2) | Expected: -3 | Actual: -3
Test 12: PASS | Input: div(7,-2) | Expected: -3 | Actual: -3
Test 13: PASS | Input: div(-7,-2) | Expected: 3 | Actual: 3
Test 14: PASS | Input: -42 | Expected: -42 | Actual: -42
Test 15: PASS | Input: 0 | Expected: 0 | Actual: 0
Test 16: PASS | Input: pow(0,0) | Expected: 1 | Actual: 1
Test 17: PASS | Input: pow(5,0) | Expected: 1 | Actual: 1
Test 18: PASS | Input: pow(-2,3) | Expected: -8 | Actual: -8
Test 19: PASS | Input: add( 10 , mul( 2 , 3 ) ) | Expected: 16 | Actual: 16
Test 20: PASS | Input: sub(add(5,2),mul(2,3)) | Expected: 1 | Actual: 1

Passed 20/20 tests